Azure APIM自定义速率限制配置报错:calls属性值无效问题求助
解决Azure APIM策略中rate-limit-by-key空值报错问题
问题背景
- 需求:仅在提供自定义速率限制值(
local.limit == true)时,才在Azure APIM策略中添加rate-limit-by-key规则,否则不添加。 - 报错信息:未提供速率限制值时触发错误:
The 'calls' attribute is invalid - The value '' is not within allowed values range。根据要求,calls是rate-limit-by-key策略的必填字段。
当前Terraform配置
variable "rate_limit" { type = string } locals { j = "context.Request.Headers.GetValueOrDefault(\"Authorization\", \"\").AsJwt()?.Subject" s = "context.Subscription.Id" limit = var.rate_limit != "" } <choose> <when condition="@((${local.j} != null || ${local.s} != null) && (${local.limit == true}))"> <rate-limit-by-key calls="${var.rate_limit}" renewal-period="60" counter-key="@(${local.j} ?? ${local.s})" /> </when> <when condition="@(context.Request.Headers.GetValueOrDefault("ApiKey") == "Default")"> <rate-limit-by-key calls="100" renewal-period="60" counter-key="@(context.Request.IpAddress)" /> </when> </choose>
生成的错误策略片段
<when condition="@((context.Request.Headers.GetValueOrDefault("Authorization", "").AsJwt()?.Subject != null || context.Subscription.Id != null) && (false))"> <rate-limit-by-key calls="" renewal-period="60" counter-key="@(context.Request.Headers.GetValueOrDefault("Authorization", "").AsJwt()?.Subject ?? context.Subscription.Id)" /> </when>
问题原因
即使<when>的条件为false,Terraform仍会渲染整个<when>节点,其中的rate-limit-by-key标签因var.rate_limit为空,导致calls属性值为空字符串。Azure APIM会校验所有存在的策略标签的必填属性,无论该标签所在的<when>条件是否会触发,因此引发报错。
解决方案
通过Terraform的条件渲染逻辑,仅在local.limit == true时才生成对应的<when>节点,彻底避免空calls属性的出现。修改后的配置如下:
variable "rate_limit" { type = string } locals { j = "context.Request.Headers.GetValueOrDefault(\"Authorization\", \"\").AsJwt()?.Subject" s = "context.Subscription.Id" limit = var.rate_limit != "" # 仅当需要自定义速率限制时,生成对应的when块内容 custom_rate_limit_rule = local.limit ? <<EOT <when condition="@((${local.j} != null || ${local.s} != null))"> <rate-limit-by-key calls="${var.rate_limit}" renewal-period="60" counter-key="@(${local.j} ?? ${local.s})" /> </when> EOT : "" } <choose> ${local.custom_rate_limit_rule} <when condition="@(context.Request.Headers.GetValueOrDefault("ApiKey") == "Default")"> <rate-limit-by-key calls="100" renewal-period="60" counter-key="@(context.Request.IpAddress)" /> </when> </choose>
修改说明
- 新增本地变量
custom_rate_limit_rule,通过三元表达式控制:当local.limit为true时,生成包含rate-limit-by-key的<when>块;否则该变量为空字符串。 - 在
<choose>节点中引用该变量,实现仅在需要时才渲染对应的速率限制规则,从根源上消除了空calls属性的问题。
内容的提问来源于stack exchange,提问作者Panda
相关产品推荐
相关产品推荐

