Hey, I am learning how to build custom policies and try to understand the difference between the effects ‘Audit’ and ‘AuditIfNotExisits’. The effect ‘AuditIfNotExists’ could have additional properties like different ‘Type’ or ‘ResourceGroupName’ properties. This allows policy evaluation in a different scope/context than that defined in the policy ‘if’ block. And a policy with an ‘AuditIfNotExisits’ effect is evaluated after a create or update request is successfully handled, unlike a policy with an ‘Audit’ effect which is evaluated before the create or update request is handled. However, for simple policy compliance check purpose, the evaluation order difference doesn’t matter.
Regarding the property ‘ExistenceCondition’ in an ‘AuditIfNotExists’ policy, generally speaking, it could be replaced logically by a condition in the if block of an ‘Audit’ policy rule, assuming the same resource ‘Type’ and the same ‘ResourceGroupName’. i.e., the following rule
{ "mode": "All", "policyRule": { "if": { <condition1> }, "then": { "effect": "AuditIfNotExists", "details": { "type": "Resource_Type", "existenceCondition": { <condition2> } } } }, "parameters": {} } |
should be equivalent to the rule
{ "mode": "All", "policyRule": { "if": { "allOf" : [ <condition1>, { "not" : <condition2> } ] }, "then": { "effect": "Audit", } }, "parameters": {} } |
But my multiple tests failed for some unknown reason. For example I have the two following rules
{ "mode": "All", "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.Compute/virtualMachines" }, { "not": { "field": "name", "like": "[concat('v','*')]" } } ] }, "then": { "effect": "Audit" } }, "parameters": {} } |
and
{ "mode": "All", "policyRule": { "if": { "field": "type", "equals": "Microsoft.Compute/virtualMachines" }, "then": { "effect": "AuditIfNotExists", "details": { "type": "Microsoft.Compute/virtualMachines", "existenceCondition": { "field": "name", "like": "[concat('v','*')]" } } } }, "parameters": {} } |
Both rules are assigned to a resource group containing two VMs: vmtest1 and server2.
The policy with the ‘Audit’ effect marked successfully the VM ‘server2’ as non-complaint resource and ‘vmtest1’ as complaint resource. However the policy with the ‘AuditIfNotExists’ effect marked both VMs as compliant resources. Even I modified the ‘existenceCondition’ to
"existenceCondition": { "field": "name", "notlike": "[concat('v','*')]" } |
Both VMs still marked as compliant.
I must make a mistake in the ‘AuditIfNotExists’ policy rule definition. Could somebody help me to figure out? Thanks