关于创建支持多作用域、同时校验特定区域与Azure DNS配置的Azure审计策略的技术咨询
Let's break down what went wrong with your original policy and fix it to properly enforce both location and DNS server checks:
Your original policy had the location validation wrapped in a not block, which inverted the logic—meaning it was effectively ignoring the specified regions instead of targeting them. We need to adjust the condition to ensure both requirements are met: the virtual network is in one of your specified regions, and its DNS server configuration exactly matches the provided array.
Here's the corrected policy:
{ "mode": "All", "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.Network/virtualNetworks" }, { "field": "location", "in": "[parameters('location')]" }, { "anyOf": [ { "value": "[empty(field('Microsoft.Network/virtualNetworks/dhcpOptions.dnsServers'))]", "equals": true }, { "value": "[not(equals(length(intersection(parameters('dnsSettings'), field('Microsoft.Network/virtualNetworks/dhcpOptions.dnsServers'))), length(parameters('dnsSettings'))))]", "equals": true }, { "value": "[not(equals(length(field('Microsoft.Network/virtualNetworks/dhcpOptions.dnsServers')), length(parameters('dnsSettings'))))]", "equals": true } ] } ] }, "then": { "effect": "[parameters('effect')]" } }, "parameters": { "dnsSettings": { "type": "Array", "metadata": { "displayName": "Required DNS Servers", "description": "List of DNS servers that must be configured on the virtual network." } }, "location": { "type": "Array", "metadata": { "displayName": "Target Regions", "description": "Regions where this policy should enforce DNS server checks.", "strongType": "location" } }, "effect": { "type": "String", "metadata": { "displayName": "Policy Effect", "description": "Enable or disable the audit for non-compliant resources." }, "allowedValues": [ "Audit", "Disabled" ], "defaultValue": "Audit" } } }
Key Changes Explained:
- Fixed Location Validation: Removed the
notwrapper around the location check—now the policy only targets virtual networks in your specified regions. - Simplified DNS Checks: Restructured the DNS validation to explicitly flag non-compliance when:
- The virtual network has no DNS servers configured
- The configured DNS servers don't include all required servers from your parameter array
- The number of configured DNS servers doesn't match the number of required servers (prevents extra/unapproved servers from being added)
- Clearer Logic Flow: The
allOfcondition ensures we only evaluate DNS settings for resources in the correct regions, and theanyOfinside flags any DNS configuration that doesn't meet your requirements.
This policy will now audit (or disable, based on your effect setting) any virtual network in your target regions that doesn't have the exact DNS server configuration you specified.
内容的提问来源于stack exchange,提问作者capcap

