Azure Policy - Convert string to number
azure resource-manager
What to do when ARM API defines a numeric property as string and you need to compare it with another number.
July 13, 2020
A quick one. I needed to create an Azure Policy which would limit the maximum number of instances that can be set for Web Apps auto-scaling. While policies are quite straight-forward and easy to set up, this one came with a complication.
I needed to detect if the maximum number of instances was set to a number greater than 6 and deny that.
The field I evaluated was Microsoft.Insights/autoscalesettings/profiles[*].capacity.maximum
which is defined in the ARM schema as string
. Rules in Azure Policies require the data types of values used in comparisons to be the same - that means in my case writing the condition like this:
"where": {
"field": "Microsoft.Insights/autoscalesettings/profiles[*].capacity.maximum",
"greater": "6"
}
Now what happens if you compare string to string? Fun stuff of course:
- "7" is greater than "6"
- "10" is not greater than "6"
- "1" is not greater than "10"
- "2" is greater than "10"
- etc., you get the idea.
Solution? Convert the string value to number.
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Insights/autoscalesettings"
},
{
"count": {
"field": "Microsoft.Insights/autoscalesettings/profiles[*]",
"where": {
"value": "[int(first(field('Microsoft.Insights/autoscalesettings/profiles[*].capacity.maximum')))]",
"greater": 6
}
},
"greater": 0
}
]
},
"then": {
"effect": "deny"
}
field()
gets the value of a field (instead of just using its identifier) - returns array, because we're iterating over profiles with[*]
first()
return first element of the arrayint()
converts string value to number
Feedback
Found something inaccurate or plain wrong? Was this content helpful to you? Let me know!
š§ codez@deedx.cz