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
相关产品推荐
相关产品推荐

