首页 > 解决方案 > 无法使用 cloudformation 模板在 api 网关方法中调用 lambda 函数

问题描述

我正在尝试使用 CloudFormation 模板预置 Lambda 和 API Gateway,并尝试在其中一种方法中调用 Lambda,但遇到类似函数 arn 的问题是无效的。请为此提供一些解决方案

{

"AWSTemplateFormatVersion":"2010-09-09",

"Transform":"AWS::Serverless-2016-10-31",

"Description":"Testing.",

"Parameters":{
   
},
"Conditions":{
   
},
"Resources":{
   "AspNetCoreFunction":{
      "Type":"AWS::Serverless::Function",
      "Properties":{
         "Handler":"<Handler_details>",
         "Runtime":"dotnetcore3.1",
         "CodeUri":"",
         "MemorySize":256,
         "Timeout":30,
         "Role":"$Function_Role",
         "Policies":null,
      }
   },
   "gateway":{
      "Type":"AWS::ApiGateway::RestApi",
      "Properties":{
         "Name":"Test",
         "Description":"Testing",
         "ApiKeySourceType":"HEADER",
         "EndpointConfiguration":{
            "Types":[
               "REGIONAL"
            ]
         }
      }
   },            
 
   "ApiMethod":{
      "Type":"AWS::ApiGateway::Method",
      "Properties":{
         "RestApiId":{
            "Ref":"gateway"
         },
         "HttpMethod":"ANY",
         "AuthorizationType":"NONE",
         "Integration":{
            "IntegrationHttpMethod":"POST",
            "TimeoutInMillis":29000,
            "Type":"AWS_PROXY",
            "Uri":{
               "Fn::Sub":[
                  "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations",
                  {
                     "lambdaArn":{
                        "Fn::GetAtt":[
                           "AspNetCoreFunction",
                           "Arn"
                           
                        ]
                     }
                  }
               ]
            }

         }
      }
   }

}

我尝试使用下面的uri,代表上面代码中提到的uri,但仍然有同样的问题。

"uri": "Fn::Sub":["arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${AspNetCoreFunction.Arn}/invocations"]

标签: amazon-web-servicesaws-lambdaamazon-cloudformationaws-api-gatewayserverless

解决方案


我认为错误与 ARN 无关,而是与 API 网关无权调用您的函数有关。您需要添加如下内容:

{
  "AllowApiInvokations": {
    "Type": "AWS::Lambda::Permission",
    "Properties": {
      "Action": "lambda:InvokeFunction",
      "FunctionName": "<function-name>" ,
      "Principal": "apigateway.amazonaws.com"
    }
  }
}

推荐阅读