Write Azure Policy as code
In this task you'll write an Azure Policy as JSON and create it from the command line.
A custom policy definition is JSON: an if (the condition, using property aliases) and a then (the effect: Audit, Deny, Modify and so on). Keep it in Git, review it like code, and create it with the CLI or Terraform.
Make the effect a parameter so the same rule can audit in one place and deny in another. Policy stops new mistakes but doesn't fix existing resources: remediate those.
Example. Fernhill Cloud's policy repository holds 20 definitions; a pipeline creates them at the management group and assigns them with Audit first, Deny once teams are ready.
Before you start
You need: Resource Policy Contributor or Owner. Time: 20 minutes.
Where to look
- Home
- Policy
- Authoring
- Definitions
Steps
- Write rules.json (if/then) and params.json (an effect parameter with allowed values).
az policy definition create -n <name> --rules rules.json --params params.json --mode Indexed.az policy assignment create -n <name> --policy <definition> --scope <id> --params '{"effect":{"value":"Deny"}}'.- Fix existing non-compliant resources yourself.
Commands
az policy definition create -n deny-public-blob --rules rules.json --params params.json --mode Indexed
az policy assignment create -n no-public-blob --policy deny-public-blob --scope $(az group show -n <group> --query id -o tsv) --params '{"effect":{"value":"Deny"}}'
Watch out for
- Cost
- Free.
- Security
- Test with Audit before Deny, or you may block teams' deployments.
- Common mistakes
- Mode All when you meant Indexed, and an alias with a typo (the policy never matches).
Clean up
Delete the assignment, then the definition (it lives at subscription level).
Words to know
- Alias
- A policy's name for a resource property, such as Microsoft.Storage/storageAccounts/allowBlobPublicAccess.
- Effect
- What happens when the condition matches.
- Assignment
- Applying a definition to a scope.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On