从自定义授权程序中的API网关方法ARN获取AWS Lambda函数名称或ARN

时间:2017-07-26 04:41:52

标签: aws-lambda aws-api-gateway

在我的APi网关自定义授权程序中,我从事件中的API网关获取methodArn,如下所示:

methodArn: 'arn:aws:execute-api:us-east-1:account-id:api-id/stage/GET/entity'

现在,我想获取关联的Lambda名称,或者最好是与该API网关方法关联的lambda。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

只能通过AWS开发工具包重新获取Lambda。您需要执行以下步骤才能获得Lambda的实现URI。

步骤:

  • 获取API的API资源
  • 获取该资源的集成
  • 从目标URI
  • 中提取Lambda ARN

在Code中,这看起来像这样。

var aws = require('aws-sdk');
var apigateway = new aws.APIGateway();
exports.handler = (event, context, callback) => {
  //sample methodArn: 'arn:aws:execute-api:eu-west-1:1234567890:p2llm1cs/prod/GET/blah/gerfea'
  var section = event.methodArn.substring(event.methodArn.lastIndexOf(':') + 1);
  var restId = section.split('\/')[0];
  var method = section.split('\/')[2];
  var path = section.substring(section.indexOf(method) + method.length);

  //getting the resources for the given API
  var params = {
    restApiId: restId,
  };
  apigateway.getResources(params, function(err, data) {
    //iterate through all attached resources
    for (var idx = 0; idx < data.items.length; idx++) {
      var item = data.items[idx];
      if (item.path == path) {
        //get the integration for the matching resource.
        var params = {
          httpMethod: method,
          resourceId: item.id,
          restApiId: restId
        };
        apigateway.getIntegration(params, function(err, data) {
          //sample data.uri arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-1:1234567890:function:echo/invocations
          console.log(data.uri);
          callback(null, 'Hello from Lambda');
        });
      }
    }
  });
};