首页 > 解决方案 > AWS API Gateway 和 Lambda 与不同 Cloudformation 堆栈上的资源集成

问题描述

我想将 lambda 函数集成到 API 网关,这样当我对 API 网关上定义的路径执行 POST 时,Lambda 会被执行并返回一个值。

现在,在我当前的项目中,我们目前有 2 个 Cloudformation 模板: - 一个是通用模板,包含所有开发环境通用的资源定义 - 另一个非通用模板,根据作为参数传递的环境部署不同的资源(开发,产品等)。

在非泛型中,我定义了 lambda 函数,以及 Deployment 和 Stage。在通用 CF 模板中,我将 APIGateway 定义为:

Resources:
  RecargakiApiGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Body:
        swagger: "2.0"
        info:
          version: "VersionTimestamp"
          title: "Some API"
        host: "some.host"
        schemes:
          - "https"
        paths:
          /payment:
            post:
              produces:
                - "application/json"
              responses:
                "200":
                  description: "200 response"
                  schema:
                    $ref: "#/definitions/Empty"
              x-amazon-apigateway-integration:
                credentials: 
                  Fn::ImportValue:
                    "lambda-credentials-outputvalue-in-another-generic-stack"
                uri: !Sub
                  - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda::${AWS::Region}:${AWS::AccountId}:function:${lambdaName}/invocations"
                  - lambdaName: "${stageVariables.lambda_name}"
                responses:
                  default:
                    statusCode: "200"
                passthroughBehavior: "when_no_match"
                timeoutInMillis: 5000
                httpMethod: "POST"
                contentHandling: "CONVERT_TO_TEXT"
                type: "aws_proxy"
        definitions:
          Empty:
            type: "object"
            title: "Empty Schema"
      Description: "Desc"
      Name: "Name"
      EndpointConfiguration:
        Types:
          - REGIONAL

现在根据AWS 代理集成的文档,可以像这样构造 lambda uri:

arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/arn:aws:lambda::<account_id>:function:${stageVariables.<function_variable_name>}/invocations

我尝试根据该格式构建 uri,但出现此错误:

Unable to put integration on 'POST' for resource at path '/payment': Invalid function ARN or invalid uri (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException

在我见过的所有示例中,人们假设要集成的 Lambda 函数与 API Gateway 资源位于相同的 CF 模板/堆栈中,但我不知道如何在 Swagger 中引用函数的 ARN 和/或名称当函数实际上位于不同的 CF 堆栈中时,API 网关的定义。

我还尝试引用一个包含完整 URI 的阶段变量,例如:

uri: "${stageVariables.functionURI}" # the URI would be constructed in the non generic stack in the format stated by the docs

但它失败了:

Unable to put integration on 'POST' for resource at path '/payment': Invalid ARN specified in the request (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException

任何帮助是极大的赞赏。

标签: amazon-web-servicesaws-lambdaamazon-cloudformationswagger-2.0

解决方案


推荐阅读