You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CloudFormation配置Lambda附加现有API Gateway后未生成触发器求解

解决Lambda附加到现有API Gateway的CloudFormation配置问题

你的现有配置缺少两个核心部分,导致Lambda无法显示API Gateway触发器且调用可能失败,以下是修正后的完整配置及说明:

修正后的CloudFormation模板

FunctionTest:
  Type: AWS::Serverless::Function
  Properties:
    FunctionName: function-test
    CodeUri: cmd/
    VpcConfig:
      SecurityGroupIds:
        - !Ref SecGroup
      SubnetIds:
        - !Ref Subnet1
        - !Ref Subnet2

ApiGatewayResource:
  Type: AWS::ApiGateway::Resource
  Properties:
    RestApiId: !ImportValue CreatedApiGW
    ParentId: !ImportValue CreatedApiGWParentId
    PathPart: "test"

ApiGatewayMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    RestApiId: !ImportValue CreatedApiGW
    ResourceId: !Ref ApiGatewayResource
    HttpMethod: "POST"
    AuthorizationType: "NONE"
    Integration:
      Type: "AWS"
      IntegrationHttpMethod: "POST"
      Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FunctionTest.Arn}/invocations"
      IntegrationResponses:
        - StatusCode: 200
    MethodResponses:
      - StatusCode: 200

# 新增:允许API Gateway调用Lambda的权限
LambdaInvokePermission:
  Type: AWS::Lambda::Permission
  Properties:
    FunctionName: !Ref FunctionTest
    Action: lambda:InvokeFunction
    Principal: apigateway.amazonaws.com
    SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${!ImportValue CreatedApiGW}/*/POST/test"

# 修改:添加部署依赖与阶段名称
ApiGatewayDeployment:
  Type: AWS::ApiGateway::Deployment
  Properties:
    RestApiId: !ImportValue CreatedApiGW
    StageName: prod # 替换为你实际使用的API阶段名称
  DependsOn:
    - ApiGatewayMethod

关键修正点说明

  • Lambda调用权限:必须配置AWS::Lambda::Permission,否则API Gateway没有权限触发Lambda,同时Lambda控制台的触发器列表也不会显示该关联。SourceArn限制了只有指定的API路径能调用Lambda,确保权限最小化。
  • 部署依赖:添加DependsOn: ApiGatewayMethod确保API资源和方法创建完成后再执行部署,避免CloudFormation因资源创建顺序问题导致新路径不生效。
  • 响应配置:补充IntegrationResponses和MethodResponses,确保API Gateway能正确处理Lambda的返回结果,避免出现500错误。

内容的提问来源于stack exchange,提问作者alexander campos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:37:55