Search code examples
azure-policy

Blocking public ip creation on VM network interface for every resource groups except one


I created a custom Azure policy from the built-in 'Network interfaces should not have public IPs' to restrict public IPs from being used in the Azure environment, but its behavior is not what I am exactly looking for.

I would like to block the creation of any public IP, except for VMs that gets created in a specific resource group.

Here's what I got so far:

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "type",
          "equals": "Microsoft.Network/networkInterfaces"
        },
        {
          "field": "Microsoft.Network/networkInterfaces/ipconfigurations[*].publicIpAddress.id",
          "exists": true
        },
        {
          "field": "type",
          "equals": "Microsoft.Resources/subscriptions/resourceGroups"
        },
        {
          "field": "name",
          "notLike": "rg-backup-lab-001"
        }
      ]
    },
    "then": {
      "effect": "deny"
    }
  },
  "parameters": {}
}

I also tried a version using a combination of "anyOf" and "allOf", but since I would like both condition to be true, it wouldn't really help my case.

{
  "mode": "All",
  "policyRule": {
    "if": {
      "anyOf": [
        {
          "allOf": [
            {
              "field": "type",
              "equals": "Microsoft.Network/networkInterfaces"
            },
            {
              "field": "Microsoft.Network/networkInterfaces/ipconfigurations[*].publicIpAddress.id",
              "exists": true
            }
          ]
        },
        {
          "allOf": [
            {
              "field": "type",
              "equals": "Microsoft.Resources/subscriptions/resourceGroups"
            },
            {
              "field": "name",
              "notLike": "rg-backup-lab-001"
            }
          ]
        }
      ]
    },
    "then": {
      "effect": "deny"
    }
  },
  "parameters": {}
}

Any idea how to combine these statements so the creation of every public IPs (other than those from a specific resource group) gets blocked ?

Thank you in advance !


Solution

  • Found a way do do it:

        "policyRule": {
          "if": {
            "allOf": [
              {
                "field": "type",
                "equals": "Microsoft.Network/networkInterfaces"
              },
              {
                "field": "Microsoft.Network/networkInterfaces/ipconfigurations[*].publicIpAddress.id",
                "exists": true
              },
              {
                "value": "[resourceGroup().name]",
                "notEquals": "rg-backup-lab-001"
              }
            ]
          },
          "then": {
            "effect": "deny"
          }
        }
      }
    

    Thank you !