I want to add a condition that allowed me to add custom rate limit only if it is given(local.limit == true
) otherwise dont add it in policy. it works fine whe there is rate limit provided but if there is no rate limit then it gives error
The 'calls' attribute is invalid - The value '' is not within allowed values range.
as per https://learn.microsoft.com/en-us/azure/api-management/rate-limit-policy calls is required field.
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>
The plan lookslike this
<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>
I managed to fix it
locals {
j = "context.Request.Headers.GetValueOrDefault(\"Authorization\", \"\").AsJwt()?.Subject"
s = "context.Subscription.Id"
limit = var.rate_limit != ""
rate_limit_config = <<XML
<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>
XML
}
<choose>
${var.api.rate_limit != "" ? local.rate_limit_config : var.api.rate_limit}
<when condition="@(context.Request.Headers.GetValueOrDefault("ApiKey") == "Default")">
<rate-limit-by-key calls="10" renewal-period="1" counter-key="@(context.Request.IpAddress)" />
</when>