简体   繁体   English

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

[英]Get AWS Lambda Function Name or ARN from API Gateway Method ARN in Custom Authorizer

I get the following methodArn from the event payload when I invoke my Lambda Authorizer in my API Gateway:当我在我的 API 网关中调用我的 Lambda 授权器时,我从事件负载中获得以下methodArn

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

I would like to get the name of the associated Lambda or, preferably, the ARN of the Lambda associated with that API Gateway method.我想获取关联 Lambda 的名称,或者最好是与该 API 网关方法关联的 Lambda 的 ARN。

How can I do it?我该怎么做?

Retreiving the Lambda can only be done through the AWS SDK.检索 Lambda 只能通过 AWS 开发工具包完成。 You need to go through the following steps to get to the implementation URI of the Lambda.您需要通过以下步骤来获取 Lambda 的实现 URI。

Steps:步骤:

  • Get the API resources for your API为您的 API 获取 API 资源
  • Get the integration for that resource获取该资源的集成
  • Extract the Lambda ARN from the target URI从目标 URI 中提取 Lambda ARN

In Code, this would look something like this.在代码中,这看起来像这样。

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');
        });
      }
    }
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM