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

无法为带方法限流的CloudFormation UsagePlan参数化资源与方法

CloudFormation API使用计划中参数化资源路径与方法的解决方案

你遇到的错误核心原因是:CloudFormation不支持直接在YAML对象的键中使用!Ref这类函数。当你尝试用!Ref MethodName作为Throttle的键时,CloudFormation不会解析这个函数,而是直接将字符串!Ref MethodName发送给API Gateway,导致路径格式不被认可,触发400错误。

方案1:单方法参数化配置

通过!Sub将参数化的路径、速率限制值拼接成JSON字符串,CloudFormation会自动将其解析为合法的YAML对象。

示例代码:

Parameters:
  TargetMethodPath:
    Type: String
    Description: 要配置节流的API资源路径+方法,格式如"/hello/world/GET"
    Default: "/hello/world/GET"
  MethodRateLimit:
    Type: Number
    Description: 该方法的速率限制
    Default: 50
  MethodBurstLimit:
    Type: Number
    Description: 该方法的突发限制
    Default: 50

Resources:
  ApiUsagePlan:
    Type: "AWS::ApiGateway::UsagePlan"
    Properties:
      Throttle:
        RateLimit: 1000
        BurstLimit: 5000
      ApiStages:
        - ApiId: !Ref MyApiGatewayApi
          Stage: !Ref MyApiStage
          Throttle: !Sub
            - '{"${Path}": {"RateLimit": ${Rate}, "BurstLimit": ${Burst}}}'
            - Path: !Ref TargetMethodPath
              Rate: !Ref MethodRateLimit
              Burst: !Ref MethodBurstLimit

方案2:多方法批量参数化

如果需要同时配置多个方法的节流规则,可以通过参数列表结合!Split和!Join批量生成配置:

示例代码:

Parameters:
  MethodThrottleConfigs:
    Type: String
    Description: 多方法节流配置,格式为"路径1,速率1,突发1;路径2,速率2,突发2"
    Default: "/hello/world/GET,50,50;/hello/user/POST,30,30"

Resources:
  ApiUsagePlan:
    Type: "AWS::ApiGateway::UsagePlan"
    Properties:
      Throttle:
        RateLimit: 1000
        BurstLimit: 5000
      ApiStages:
        - ApiId: !Ref MyApiGatewayApi
          Stage: !Ref MyApiStage
          Throttle: !Sub
            - '{$Configs}'
            - Configs: !Join
                - ","
                - !Split
                    - ";"
                    - !Sub
                      - '"${Path}": {"RateLimit": ${Rate}, "BurstLimit": ${Burst}}'
                      - Path: !Select [0, !Split [",", !Ref MethodThrottleConfigs]]
                        Rate: !Select [1, !Split [",", !Ref MethodThrottleConfigs]]
                        Burst: !Select [2, !Split [",", !Ref MethodThrottleConfigs]]

关键注意事项

  • 路径格式必须严格遵循API Gateway要求:/resource-path/HTTP-Method(例如/hello/world/GET)
  • 速率限制和突发限制参数必须是数字类型,!Sub中不需要添加引号
  • 如果引用其他资源的属性作为路径,确保属性值符合格式要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:14:52