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:

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"
  }
  1. field() gets the value of a field (instead of just using its identifier) - returns array, because we’re iterating over profiles with [*]
  2. first() return first element of the array
  3. int() converts string value to number

comments powered by Disqus