Search code examples
azureazure-policy

Azure Policy - Target Specific Entry in Array


I need to enable Network Policy (Route Table) for private endpoints in Azure. I've got a working Azure policy (shown below for reference), however this targets all subnets. Whilst this isn't really an issue (as the setting only applies to private endpoints anyway), I'd prefer to be more targeted, just to prevent confusion and in case any future weird bugs.

What I'm looking to do is only perform the modification ONLY on subnets with a specific name (e.g. snet-plink) - is this possible? I've had a bit of a play around and reviewed the docs, but I've not been able to achieve this yet.

Current working (broad) policy shown below:

{
    "mode": "All",
    "policyRule": {
      "if": {
        "field": "Microsoft.Network/virtualNetworks/subnets[*].privateEndpointNetworkPolicies",
        "notIn": [
            "RouteTableEnabled",
            "Enabled"
        ]
      },
      "then": {
        "effect": "modify",
        "details": {
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/4d97b98b-1d4f-4787-a291-c67834d212e7"
          ],
          "operations": [
            {
              "operation": "addOrReplace",
              "field": "Microsoft.Network/virtualNetworks/subnets[*].privateEndpointNetworkPolicies",
              "value": "RouteTableEnabled"
            }
          ]
        }
      }
    },
    "parameters": {}
  }

I've looked to see if there is a selector option for the array (like you have with jmespath) but this doesn't seem to exist with Azure policy. I've also explored count as an option, but again I don't think this will help me unfortunately with the modify effect.


Solution

  • I've since had chance to spend some time playing with this and have come up with an approach that works.

    {
      "mode": "All",
      "policyRule": {
        "if": {
          "allOf": [
            {
              "field": "type",
              "equals": "Microsoft.Network/virtualNetworks/subnets"
            },
            {
              "field": "name",
              "equals": "snet-plink"
            },
            {
              "field": "Microsoft.Network/virtualNetworks/subnets/privateEndpointNetworkPolicies",
              "equals": "Disabled"
            }
          ]
        },
        "then": {
          "effect": "modify",
          "details": {
            "roleDefinitionIds": [
              "/providers/Microsoft.Authorization/roleDefinitions/4d97b98b-1d4f-4787-a291-c67834d212e7"
            ],
            "operations": [
              {
                "operation": "addOrReplace",
                "field": "Microsoft.Network/virtualNetworks/subnets/privateEndpointNetworkPolicies",
                "value": "RouteTableEnabled"
              }
            ]
          }
        }
      },
      "parameters": {}
    }