CloudFormation部署后Lambda与API Gateway触发器异常排查
问题原因及解决方案
核心问题分析
你的CloudFormation模板存在4个关键错误,直接导致API Gateway触发器显示异常:
- Lambda集成URI版本错误:API Gateway调用Lambda的代理集成必须使用固定API版本
2015-03-31,而非自定义的2024-01-21,该版本号为AWS官方规定的固定值,不可随意修改。 - 集成HttpMethod配置错误:
AWS_PROXY类型的集成要求IntegrationHttpMethod必须设为POST,不管API对外暴露的是哪种HttpMethod,否则API Gateway无法正确转发请求到Lambda。 - 无效路径参数配置:在根资源(
RootResourceId)上声明了method.request.path.parameter路径参数,但根路径本身不存在该参数,导致API方法配置不合法,触发关联失败。 - Lambda权限SourceArn格式错误:当前权限的SourceArn末尾多了斜杠,会导致权限匹配失败,API Gateway无法正常调用Lambda。
修复后的完整模板
AWSTemplateFormatVersion: "2010-09-09" Description: "My API Gateway and Lambda function" Resources: SampleApi: Type: "AWS::ApiGateway::RestApi" Properties: Name: Sample SampleApiMethod: Type: "AWS::ApiGateway::Method" Properties: AuthorizationType: "NONE" HttpMethod: "GET" Integration: IntegrationHttpMethod: "POST" Type: "AWS_PROXY" Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${SampleLambda.Arn}/invocations" ResourceId: !GetAtt "SampleApi.RootResourceId" RestApiId: !Ref "SampleApi" SampleApiDeployment: Type: "AWS::ApiGateway::Deployment" DependsOn: "SampleApiMethod" Properties: RestApiId: !Ref "SampleApi" StageName: test SampleLambda: Type: "AWS::Lambda::Function" Properties: Code: ZipFile: | def handler(event,context): return { 'body': 'Hello, world!', 'headers': { 'Content-Type': 'text/plain' }, 'statusCode': 200 } Handler: "index.handler" Role: !GetAtt "SampleLambdaRole.Arn" Runtime: python3.10 LambdaApiGatewayInvoke: Type: "AWS::Lambda::Permission" Properties: Action: "lambda:InvokeFunction" FunctionName: !GetAtt "SampleLambda.Arn" Principal: "apigateway.amazonaws.com" SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${SampleApi}/*/GET" SampleLambdaRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Action: ["sts:AssumeRole"] Effect: "Allow" Principal: Service: ["lambda.amazonaws.com"] Policies: - PolicyDocument: Version: "2012-10-17" Statement: - Action: ["cloudwatch:*", "logs:*"] Effect: "Allow" Resource: "*" PolicyName: "lambdaLogPolicy" SampleLambdaLogGroup: DependsOn: SampleLambda Type: "AWS::Logs::LogGroup" Properties: LogGroupName: !Sub "/aws/lambda/${SampleLambda}"
验证步骤
- 删除现有CloudFormation堆栈,避免残留错误配置。
- 使用修正后的模板重新创建堆栈,保持默认配置即可。
- 堆栈创建完成后,查看Lambda函数的触发器,API Gateway关联应显示正常。
- 可通过API Gateway的测试URL调用,验证是否返回
Hello, world!内容。
内容的提问来源于stack exchange,提问作者beloas
相关产品推荐
相关产品推荐

