{
    "type": "Microsoft.Authorization/policyDefinitions",
    "name": "enforce-nsg-on-subnet",
    "properties": {
        "displayName": "NSG X on every subnet",
        "description": "This policy enforces a specific NSG on every subnet",
        "mode": "All",
        "parameters": {
            "nsgId": {
                "type": "String",
                "metadata": {
                    "description": "Resource Id of the Network Security Group",
                    "displayName": "NSG Id"
                }
            }
        },
        "policyRule": {
            "if": {
                "anyOf": [
                    {
                        "allOf": [
                            {
                                "field": "type",
                                "equals": "Microsoft.Network/virtualNetworks"
                            },
                            {
                                "not": {
                                    "field": "Microsoft.Network/virtualNetworks/subnets[*].networkSecurityGroup.id",
                                    "equals": "[parameters('nsgId')]"
                                }
                            }
                        ]
                    },
                    {
                        "allOf": [
                            {
                                "field": "type",
                                "equals": "Microsoft.Network/virtualNetworks/subnets"
                            },
                            {
                                "not": {
                                    "field": "Microsoft.Network/virtualNetworks/subnets/networkSecurityGroup.id",
                                    "equals": "[parameters('nsgId')]"
                                }
                            }
                        ]
                    }
                ]
            },
            "then": {
                "effect": "deny"
            }
        }
    }
}