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

如何使用CloudFormation将Lambda函数绑定到已有的API Gateway

解决方案

方法1:参数传入(无需额外开发,优先推荐)

这是最稳妥的CloudFormation原生实现方式,直接把目标资源的ID作为栈参数传入模板即可,无需额外工具:

  • 模板示例如下:
Parameters:
  ExistingRestApiId:
    Type: String
    Description: 已有API Gateway的RestApiId
  ExistingResourceId:
    Type: String
    Description: 待绑定路径对应的节点ResourceId
  TargetLambdaArn:
    Type: String
    Description: 要绑定的Lambda函数ARN

Resources:
  # 绑定Lambda的API Method
  TargetApiMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      RestApiId: !Ref ExistingRestApiId
      ResourceId: !Ref ExistingResourceId
      HttpMethod: POST # 替换为实际需要的请求方法
      AuthorizationType: NONE
      Integration:
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${TargetLambdaArn}/invocations

  # 给API Gateway添加调用Lambda的权限,否则请求会报错
  LambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref TargetLambdaArn
      Action: lambda:InvokeFunction
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ExistingRestApiId}/*/POST/*
  • 如果你不想手动在控制台查ID,可以用AWS CLI提前查询对应值后再传入栈:
    • 查询所有API Gateway的名称和对应RestApiId:aws apigateway get-rest-apis --query "items[].[name,id]" --output table
    • 查询指定RestApi下所有路径和对应ResourceId:aws apigateway get-resources --rest-api-id <替换为上一步查到的RestApiId> --query "items[].[path,id]" --output table

方法2:SSM参数动态引用

如果你的团队已经将现有API Gateway的ID统一存储在AWS Systems Manager Parameter Store中,可以直接在模板中动态拉取,不需要手动传参:

Resources:
  TargetApiMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      RestApiId: !Sub '{{resolve:ssm:/你的/SSM参数路径/restApiId}}'
      ResourceId: !Sub '{{resolve:ssm:/你的/SSM参数路径/resourceId}}'
      # 其余配置同方法1

方法3:自定义Lambda资源(仅需动态匹配时使用)

如果需要在栈部署过程中自动按API名称、路径名匹配查询ID,才需要借助Lambda自定义资源实现:

  • Lambda逻辑只需要调用get_rest_apis和get_resources接口按名称过滤,返回对应ID即可
  • 需要给Lambda对应的IAM角色添加apigateway:GET权限

注意事项

如果需要修改后的API立即生效,需要额外添加AWS::ApiGateway::Deployment资源关联到对应部署阶段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 15:33:02