Azure Policy: rules that say no (deny, audit, scopes and exclusions)
RBAC answers who may do something. Azure Policy answers what may exist, whoever creates it: only these regions, every resource tagged with a cost centre, no public IPs in production, storage accounts never open to the internet. It is the platform team's guardrail, and on-call meets it both ways: as the reason a 6 pm deploy fails with RequestDisallowedByPolicy, and as the compliance report that shows which of last year's resources break today's rules.
Need to know:
| Object | What it is |
|---|---|
| Policy definition | one rule as JSON: if (conditions on the resource's fields) / then (an effect), plus parameters. Hundreds are built-in; you can write custom ones. |
| Initiative (policy set definition) | a bundle of definitions assigned together, e.g. a security baseline. Next lesson. |
| Assignment | a definition or initiative applied at a scope (management group, subscription, resource group) with parameter values, optional exclusions (notScopes), an enforcement mode and non-compliance messages. Nothing happens until you assign. |
| Exemption | one scope or resource taken out of one assignment, with a reason and an expiry date. |
| Compliance state | the result of evaluating existing resources: Compliant, NonCompliant, Exempt... |
The effects, in the order Azure applies them to a create or update request:
| Effect | What it does |
|---|---|
disabled | nothing (switch a rule off without unassigning it) |
append / modify | change the request before it is stored: add a tag, set a property (next lesson) |
deny | refuse the request: 403 RequestDisallowedByPolicy |
audit | let it through, mark the resource non-compliant |
auditIfNotExists / deployIfNotExists | after the write, look for a related resource (a backup, a diagnostic setting); report it missing or deploy it |
Reading a built-in definition
$ az policy definition list --query "[?policyType=='BuiltIn' && metadata.category!='Backup'].{name:displayName, effect:policyRule.then.effect}" -o table
Name Effect
----------------------------------------------------- ----------------------
Allowed locations deny
Allowed locations for resource groups deny
Require a tag on resources deny
Require a tag and its value on resources deny
Require a tag on resource groups deny
Inherit a tag from the resource group if missing modify
Add a tag to resources modify
Not allowed resource types [parameters('effect')]
Allowed virtual machine size SKUs Deny
Network interfaces should not have public IPs deny
Audit VMs that do not use managed disks audit
Secure transfer to storage accounts should be enabled [parameters('effect')]
Storage accounts should restrict network access [parameters('effect')]
$ az policy definition show -n e56962a6-4747-49cd-b67b-bf8b01975c4c --query "{name:displayName, mode:mode, params:keys(parameters), rule:policyRule}"
{
"mode": "Indexed",
"name": "Allowed locations",
"params": [
"listOfAllowedLocations"
],
"rule": {
"if": {
"allOf": [
{
"field": "location",
"notIn": "[parameters('listOfAllowedLocations')]"
},
{
"field": "location",
"notEquals": "global"
},
{
"field": "type",
"notEquals": "Microsoft.AzureActiveDirectory/b2cDirectories"
}
]
},
"then": {
"effect": "deny"
}
}
}
- The name of a built-in is a GUID (
e56962a6-...is Allowed locations everywhere, in every tenant). Assign by that name or the full id; display names are not unique. [parameters('effect')]means the assignment chooses the effect (Audit, Deny, Disabled). Start new rules on Audit, read the compliance report, then switch to Deny. Then the first denial in a pipeline is not also the first time anyone hears about the rule.mode: Indexedevaluates only resource types that support tags and location.Allalso covers resource groups and subscriptions. Allowed locations is Indexed, so it does not stop a resource group in eastus: there is a separate built-in, Allowed locations for resource groups.
Assigning, with an exclusion
The lab subscription should only get resources in West and North Europe, except the engineers' sandbox group:
$ az group create -n rg-try-policy -l westeurope -o none
$ az group create -n rg-try-sandbox -l westeurope -o none
$ az policy assignment create -n try-allowed-loc --display-name "Allowed locations (West/North Europe)" --policy e56962a6-4747-49cd-b67b-bf8b01975c4c --scope /subscriptions/00000000-1111-2222-3333-444444444444 -p '{"listOfAllowedLocations":{"value":["westeurope","northeurope"]}}' --not-scopes /subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-try-sandbox --query "{name:name, scope:scope, notScopes:notScopes, enforcement:enforcementMode}"
{
"enforcement": "Default",
"name": "try-allowed-loc",
"notScopes": [
"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-try-sandbox"
],
"scope": "/subscriptions/00000000-1111-2222-3333-444444444444"
}
Now a create outside the allowed regions:
$ az storage account create -n sttrypol01 -g rg-try-policy -l eastus -o none
ERROR: (RequestDisallowedByPolicy) Resource 'sttrypol01' was disallowed by policy. Policy identifiers: '[{"policyAssignment":{"name":"Allowed locations (West/North Europe)","id":"/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Authorization/policyAssignments/try-allowed-loc"},"policyDefinition":{"name":"Allowed locations","id":"/providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd-b67b-bf8b01975c4c","version":"1.0.0"}}]'.
Code: RequestDisallowedByPolicy
Message: Resource 'sttrypol01' was disallowed by policy. Policy identifiers: '[{"policyAssignment":{"name":"Allowed locations (West/North Europe)","id":"/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Authorization/policyAssignments/try-allowed-loc"},"policyDefinition":{"name":"Allowed locations","id":"/providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd-b67b-bf8b01975c4c","version":"1.0.0"}}]'.
Target: sttrypol01
Additional Information:Type: PolicyViolation
Info: {
"evaluationDetails": {
"evaluatedExpressions": [
{
"result": "True",
"expressionKind": "Field",
"expression": "location",
"path": "location",
"expressionValue": "eastus",
"targetValue": [
"westeurope",
"northeurope"
],
"operator": "NotIn"
},
{
"result": "True",
"expressionKind": "Field",
"expression": "location",
"path": "location",
"expressionValue": "eastus",
"targetValue": "global",
"operator": "NotEquals"
},
{
"result": "True",
"expressionKind": "Field",
"expression": "type",
"path": "type",
"expressionValue": "Microsoft.Storage/storageAccounts",
"targetValue": "Microsoft.AzureActiveDirectory/b2cDirectories",
"operator": "NotEquals"
}
]
},
"policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd-b67b-bf8b01975c4c",
"policyDefinitionName": "e56962a6-4747-49cd-b67b-bf8b01975c4c",
"policyDefinitionDisplayName": "Allowed locations",
"policyDefinitionVersion": "1.0.0",
"policyDefinitionEffect": "deny",
"policyAssignmentId": "/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Authorization/policyAssignments/try-allowed-loc",
"policyAssignmentName": "try-allowed-loc",
"policyAssignmentDisplayName": "Allowed locations (West/North Europe)",
"policyAssignmentScope": "/subscriptions/00000000-1111-2222-3333-444444444444",
"policyAssignmentParameters": {
"listOfAllowedLocations": [
"westeurope",
"northeurope"
]
},
"policyExemptionIds": [],
"policyEnrollmentIds": []
}
Read the error from the top: RequestDisallowedByPolicy, the assignment (name and id: this tells you who to talk to, and at which scope it lives), the definition, then evaluationDetails: every expression, the value your request had (eastus) and what the rule expected. That is enough to fix the request without opening the portal. In the sandbox the same create goes through, because notScopes excludes it:
$ az storage account create -n sttrypol02 -g rg-try-sandbox -l eastus -o none && echo created
created
A non-compliance message turns the wall of JSON into an instruction:
$ az policy assignment non-compliance-message create -n try-allowed-loc -m "Only westeurope or northeurope (data residency). Exemptions: #platform." -o none
$ az storage account create -n sttrypol01 -g rg-try-policy -l eastus -o none 2>&1 | head -1
ERROR: (RequestDisallowedByPolicy) Resource 'sttrypol01' was disallowed by policy. Reasons: 'Only westeurope or northeurope (data residency). Exemptions: #platform.'. See error details for policy resource IDs.
Enforcement mode and existing resources
--enforcement-mode DoNotEnforceevaluates and reports compliance but never denies or modifies. Use it to see what would break before you turn a rule on.- Policy does not delete or change existing resources when you assign a deny. An account already in eastus stays there and shows as non-compliant. Deny only acts on the next create or update of that resource, and an update to an old non-compliant resource will be denied. That is a common surprise: "I only changed a tag and the policy blocked me".
Compliance
A new assignment is evaluated within about 30 minutes, then once every 24 hours and on every change to a resource. Waiting is not an option during an incident: trigger-scan evaluates now.
$ az policy state summarize -g rg-try-sandbox --query "results.nonCompliantResources"
0
$ az policy assignment create -n try-secure-transfer --policy 404c3081-a854-4457-ae30-26a93ef643f9 -g rg-try-sandbox -o none
$ az storage account update -n sttrypol02 -g rg-try-sandbox --https-only false -o none
$ az policy state trigger-scan -g rg-try-sandbox
$ az policy state list -g rg-try-sandbox --filter "complianceState eq 'NonCompliant'" --query "[].{resource:resourceId, assignment:policyAssignmentName, effect:policyDefinitionAction}" -o table
Resource Assignment Effect
---------------------------------------------------------------------------------------------------------------------------------------- ------------------- ------
/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-try-sandbox/providers/Microsoft.Storage/storageAccounts/sttrypol02 try-secure-transfer audit
$ az policy state summarize -g rg-try-sandbox --query "results.{nonCompliantResources:nonCompliantResources, nonCompliantPolicies:nonCompliantPolicies}"
{
"nonCompliantPolicies": 1,
"nonCompliantResources": 1
}
- The account in the sandbox is excluded from Allowed locations (notScopes), but not from the secure-transfer audit assigned on the sandbox group itself. Exclusions are per assignment.
state listis per resource per assignment.summarizecounts them. The portal's Compliance page is the same data.
Exemptions: the right way to say "not here"
When one resource must break a rule (a legacy app that needs an eastus account until March), do not delete the assignment and do not add a notScope you will forget. Create an exemption: scoped to that resource, with a category (Waiver = accepted risk, Mitigated = handled another way) and an expiry.
$ az policy exemption create -n try-legacy-east --policy-assignment /subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Authorization/policyAssignments/try-allowed-loc --scope /subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-try-policy --exemption-category Waiver --expires-on 2027-03-31T00:00:00Z --description "INC-4411: legacy reporting until the March migration" --query "{name:name, category:exemptionCategory, expires:expiresOn}"
{
"category": "Waiver",
"expires": "2027-03-31T00:00:00Z",
"name": "try-legacy-east"
}
$ az storage account create -n sttrypol01 -g rg-try-policy -l eastus -o none && echo created
created
Exemptions show up as Exempt in compliance, appear in audits with their reason, and stop on their own date. A notScope lasts until someone notices it.
On the exam (AZ-104 1.3.1): definitions vs initiatives vs assignments, the effects and their order, scopes and inheritance, exclusions vs exemptions, enforcement mode, parameters, compliance (30 minutes, trigger-scan), "existing resources are not changed by deny". Expect "which effect" and "why was this deployment blocked" questions.
In an interview: "A deployment fails with RequestDisallowedByPolicy. What do you do?" - "Read the error: it names the assignment and the definition, and the evaluation details show which field had which value. Then I fix the request, for example the region or a missing tag, because the policy is usually right. If this resource really needs an exception, it gets a policy exemption scoped to it, with a reason and an expiry. I don't delete the assignment and I don't widen notScopes."
What you can now do
- Read a definition's rule, parameters and mode, and pick the right built-in.
- Assign it at a scope with parameters, exclusions and a non-compliance message.
- Read a
RequestDisallowedByPolicyerror and say what to change. - Get compliance now with
trigger-scan, and list what is non-compliant. - Use an exemption with an expiry instead of deleting a guardrail.