How to Use Azure Policy: Simple Guide for Beginners
Use
Azure Policy to create rules that enforce how resources are configured in your Azure environment. Define a policy definition, assign it to a scope like a subscription or resource group, and Azure will evaluate and enforce compliance automatically.Syntax
An Azure Policy setup involves three main parts:
- Policy Definition: The rule you want to enforce, written in JSON.
- Policy Assignment: Applying the policy to a specific scope like a subscription or resource group.
- Policy Parameters: Optional values to customize the policy behavior.
json
{
"policyRule": {
"if": {
"field": "<resource-property>",
"equals": "<value>"
},
"then": {
"effect": "<deny|audit|append|modify|deployIfNotExists>"
}
},
"parameters": {
"<parameter-name>": {
"type": "String",
"metadata": {
"description": "Description of the parameter",
"displayName": "Parameter Display Name"
}
}
}
}Example
This example creates a policy that denies creation of virtual machines in a specific location, then assigns it to a subscription.
json + bash
{
"properties": {
"displayName": "Deny VMs outside East US",
"policyType": "Custom",
"mode": "All",
"description": "Deny creating VMs outside East US region.",
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Compute/virtualMachines"
},
{
"field": "location",
"notEquals": "eastus"
}
]
},
"then": {
"effect": "deny"
}
}
}
}
// Assign the policy using Azure CLI
az policy assignment create --name "deny-vm-outside-eastus" --policy <policy-definition-id> --scope /subscriptions/<subscription-id>Output
Policy definition created and assigned successfully.
New VM creation outside eastus will be denied.
Common Pitfalls
Common mistakes when using Azure Policy include:
- Not assigning the policy after creating it, so it has no effect.
- Using incorrect scopes, like assigning to a resource group but expecting subscription-wide enforcement.
- Choosing the wrong
effectlikeauditwhen you want to block actions. - Forgetting to test policies in a non-production environment first.
json
{
"wrong": {
"effect": "audit"
},
"right": {
"effect": "deny"
}
}Quick Reference
| Concept | Description |
|---|---|
| Policy Definition | JSON rule that describes what to enforce |
| Policy Assignment | Applying the policy to a subscription, resource group, or management group |
| Effect | Action taken when rule matches: deny, audit, append, modify, deployIfNotExists |
| Scope | The target resources where the policy applies |
| Parameters | Customizable inputs to make policies flexible |
Key Takeaways
Create a policy definition in JSON to specify rules for your Azure resources.
Assign the policy to a subscription or resource group to enforce it.
Choose the correct effect like deny to block unwanted resource configurations.
Test policies in a safe environment before applying to production.
Use parameters to customize policies for different scenarios.