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

如何通过CloudFormation配置API Gateway VPC Link的「使用阶段变量」参数

问题描述

我正尝试通过CloudFormation创建API Gateway配置,需实现启用「使用阶段变量」选项的VPC Link配置,即选择该选项并使用自定义变量如${stageVariables.vpclink_example}。

当前我的CloudFormation模板代码片段如下:

ProxyAnyMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: CUSTOM
    HttpMethod: ANY
    ResourceId: !Ref DynamicProxyResource
    RestApiId: !FindInMap [ApiSettings, ApiConfig, RestApiId]
    Integration:
      IntegrationHttpMethod: ANY
      Type: HTTP_PROXY
      Uri: "http://${stageVariables.vpclink_example_nlb}/example/api/{proxy}"
      ConnectionType: VPC_LINK
      ConnectionId: "vpclink_example"

但收到错误提示:

ConnectionId should be set to the vpcLinkId or stage variable on connection type VPC_LINK

此前尝试过两种方法均失败:

  • 在ConnectionId字段传入${stageVariables.vpclink_example},但CloudFormation期望该字段为明确的VPC Link ID而非运行时变量,导致报错。
  • 在模板中定义参数接收VPC Link值并传入ConnectionId,但CloudFormation无法自动启用控制台的「使用阶段变量」选项,导致VPC Link值固定,不依赖阶段上下文。

我的问题是:如何直接在CloudFormation模板中为API Gateway的VPC Link配置「使用阶段变量」选项?我未找到相关文档。是否有替代方案可通过CloudFormation实现该配置?若无法实现,部署时还有哪些配置方式?


解决方案

1. CloudFormation直接配置的正确写法

CloudFormation的AWS::ApiGateway::Method资源中,要启用VPC Link的阶段变量,需在ConnectionId字段用双引号包裹阶段变量语法,让CloudFormation识别这是运行时变量而非静态ID。正确模板如下:

ProxyAnyMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: CUSTOM
    HttpMethod: ANY
    ResourceId: !Ref DynamicProxyResource
    RestApiId: !FindInMap [ApiSettings, ApiConfig, RestApiId]
    Integration:
      IntegrationHttpMethod: ANY
      Type: HTTP_PROXY
      Uri: "http://${stageVariables.vpclink_example_nlb}/example/api/{proxy}"
      ConnectionType: VPC_LINK
      # 用双引号包裹阶段变量语法,让CloudFormation识别为运行时变量
      ConnectionId: "${stageVariables.vpclink_example}"
      PassthroughBehavior: WHEN_NO_MATCH

注意:必须保留双引号,否则CloudFormation会将其当作静态字符串校验,导致报错。

2. 替代方案:部署后用CLI更新

如果CloudFormation模板仍无法生效,可在部署完成后通过AWS CLI修改集成配置,强制启用阶段变量:

aws apigateway update-integration \
    --rest-api-id YOUR_REST_API_ID \
    --resource-id YOUR_RESOURCE_ID \
    --http-method ANY \
    --patch-operations '[
        {
            "op": "replace",
            "path": "/connectionId",
            "value": "${stageVariables.vpclink_example}"
        }
    ]'

3. 控制台手动配置(应急方案)

若自动化方式无法满足需求,可在CloudFormation部署完成后手动操作:

  • 进入API Gateway控制台,找到目标方法的「集成请求」配置
  • 在「VPC链接」区域勾选「使用阶段变量」
  • 输入框中填入${stageVariables.vpclink_example}
  • 保存配置并重新部署API阶段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:12:43