Apply policy, tags and resource locks
Enforce tags and allowed regions with Azure Policy, protect resources with locks, and recover from a blocked deployment.
By Invicly Tech, , in Microsoft Azure Cloud Engineering. About 13 minutes to read.
In short
Azure Policy checks the properties of resources against rules, for example that every resource has a cost-centre tag or lives in an allowed region. Depending on the effect, it can block a request (deny), only report it (audit) or change it (modify). Resource locks are a separate guardrail that stop deletion or changes even by people whose role allows them, which makes them a good last line of defence for important resources.
Think of it like this: RBAC decides who may enter the kitchen, policy is the house rules about what can be cooked, and a lock is the cover over the gas tap.
Explained simply
RBAC decides who may make changes. But even trusted people make mistakes: they create a database in the wrong country, forget a cost tag, or delete the wrong thing. Azure Policy and resource locks catch those mistakes.
Azure Policy compares resources against rules. A rule might say every resource must have a cost-centre tag, or only West Europe and North Europe are allowed. When someone creates or updates a resource, policy checks it. Depending on the rule, it blocks the request, lets it through but reports it, or adjusts it, for example by adding a missing tag.
Policy also scans what already exists and shows a compliance score, so you can see how many resources break a rule. That makes it safe to start with a rule that only reports, look at the results, and switch to blocking later.
A resource lock is simpler. You put it on a resource, resource group or subscription, and it stops deletion (or, with ReadOnly, any change) by anyone, even an Owner, until the lock is removed. It turns a dangerous delete into a two-step, deliberate act.
Press Play on a diagram to walk through it one step at a time.
- 1Request
PUT a storage account in rg-lab-api
- 2RBAC
Is the caller allowed this action at this scope?
- 3Locks
Is a lock on the resource or a parent blocking it?
- 4Azure Policy
Modify fixes the request; deny rejects it; audit only records it
- 5Resource provider
Creates or updates the resource
- Blocks the create or update
- Error RequestDisallowedByPolicy
- Use for hard rules such as regions
- Existing resources are only reported
- Allows the request
- Marks the resource non-compliant
- Safe first step for a new rule
- Shows impact before you enforce
- Adds or changes tags or properties
- Needs a managed identity on the assignment
- Fixes existing resources with a remediation task
- Good for inheriting tags
- Who can act
- Azure RBAC role assignments
- What resources may look like
- Policy with deny for hard rules
- Policy with audit to measure first
- Missing or inconsistent settings
- Policy with modify or deployIfNotExists
- Remediation task for existing resources
- Accidental deletion
- CanNotDelete lock
- Soft delete for data inside
In depth
Definitions, initiatives and assignments
A policy definition is a JSON rule with an if condition and a then effect. Azure ships hundreds of built-in definitions, such as Allowed locations, Require a tag on resources and Inherit a tag from the resource group if missing. Definitions take parameters, such as the list of allowed regions or the tag name.
An initiative, also called a policy set, groups several definitions, such as a security benchmark, so you assign them in one go. An assignment applies a definition or initiative at a scope with parameter values. Like RBAC, assignments are inherited downwards, and you can exclude child scopes. An assignment can also run with enforcement mode DoNotEnforce, which evaluates and reports compliance but never blocks or modifies, a useful way to trial a rule.
- Definition: the rule and its effect
- Initiative: several definitions together
- Assignment: rule plus scope plus parameter values
- Exclusions and exemptions carve out exceptions
Effects: deny, audit, modify and friends
Deny rejects a create or update that breaks the rule, with the error RequestDisallowedByPolicy. Existing resources that break it are marked non-compliant but not changed. Audit allows the request and records a non-compliant result. Modify adds, replaces or removes tags and some properties during the request; it needs a managed identity on the assignment with a role such as Tag Contributor, and fixes existing resources only through a remediation task. Append adds fields, AuditIfNotExists and DeployIfNotExists look at a related resource, such as diagnostic settings, and DenyAction blocks specific actions such as delete.
When several assignments apply, Azure evaluates them in a set order: Disabled first, then Append and Modify, then Deny, then Audit. This means a Modify policy that adds a missing tag runs before a Deny policy that requires the tag, so the two work well together.
- 1Disabled
Checked first; the rule is skipped.
- 2Append and Modify
Request is changed, for example a tag added.
- 3Deny
Changed request is checked; non-compliant requests stop.
- 4Audit
Allowed request is logged as non-compliant if it breaks a rule.
Requiring and inheriting tags
Tag rules are the classic first policies. Require a tag on resource groups makes every new group carry, say, cost-centre. Inherit a tag from the resource group if missing then copies that value onto resources as they are created or updated. Together they give consistent cost reports with no extra effort for engineers.
Two details matter. Most tag definitions use the Indexed mode, which only evaluates resource types that support tags and location, so they do not break deployments of types that cannot be tagged. And existing resources are not fixed by Modify until you run a remediation task: az policy remediation create targets the assignment and processes existing non-compliant resources. Check the results in the compliance view, then repeat for other scopes.
- Require on groups, inherit to resources
- Modify needs an assignment identity with a tag role
- Remediation tasks fix existing resources
- Use the same tag names your budgets and reports use
Locks: CanNotDelete and ReadOnly
Locks have two levels. CanNotDelete, shown as Delete in the portal, allows reads and changes but blocks deletion. ReadOnly blocks deletion and every change, which sounds safer but often breaks things: listing storage account keys is a POST action and is blocked, and some services cannot scale or update under a ReadOnly lock. Use CanNotDelete for production resources and shared infrastructure, and ReadOnly only where you understand the side effects.
Locks are inherited, apply to everyone, and only affect the control plane. A lock on a storage account stops someone deleting the account, but not deleting blobs inside it; use soft delete and versioning for that. Creating and removing locks needs Microsoft.Authorization/locks permissions, which Owner and User Access Administrator have. A CanNotDelete lock on any resource in a group also blocks deleting the whole group.
- CanNotDelete: change yes, delete no
- ReadOnly: no changes, can break normal operations
- Locks do not protect data inside a resource
- Owner or User Access Administrator manages locks
Diagnosing and recovering from a blocked deployment
When a deployment fails, read the error code first. RequestDisallowedByPolicy means a deny policy matched; the error details name the policy assignment and definition, and often the field that failed. ScopeLocked means a lock blocked the operation. AuthorizationFailed is RBAC, not policy.
Then choose the right fix. Most of the time the template is wrong: change the region, add the tag, or pick an allowed SKU, and redeploy. If the resource genuinely needs an exception, create a policy exemption with a category (Waiver or Mitigated), a reason and an expiry date, scoped as narrowly as possible. Avoid deleting or loosening the assignment for everyone. For locks, remove the lock deliberately, do the change, and put it back. The Activity log keeps a record of the denied operations for later review.
Learn it in 5 short steps
About 25m each. Track them with a timer in your plan.
- 1Assign a built-in policy~25m
- 2Compare deny, audit and modify~25m
- 3Require tags~25m
- 4Add a delete lock~25m
- 5Diagnose a policy denial~25m
Key points
- Policy is about what resources look like; RBAC is about who can act. You usually need both.
- Start new rules with audit, check the compliance results, then switch to deny.
- There are two lock levels: CanNotDelete (shown as Delete in the portal) and ReadOnly.
- Locks are inherited by child resources and apply to everyone, including Owners, until removed.
- ReadOnly locks can break normal operations, such as listing storage keys, so prefer CanNotDelete.
Key terms
Tap a card to flip it. 0/6 known
Examples
RG_ID=$(az group show --name rg-lab-api --query id -o tsv)
DEF=$(az policy definition list \
--query "[?displayName=='Allowed locations'].name | [0]" -o tsv)
az policy assignment create --name allowed-locations \
--policy "$DEF" --scope "$RG_ID" \
--params '{"listOfAllowedLocations":{"value":["westeurope","northeurope"]}}'
az lock create --name keep-kv --lock-type CanNotDelete \
--resource-group rg-lab-api --resource-type Microsoft.KeyVault/vaults \
--resource kv-lab-apiRestrict regions for one resource group and protect a key vault from deletion.
Requiring a cost-centre tag without breaking anyone
Prerequisites: Owner or Resource Policy Contributor on the subscription (plus rights to assign roles for the modify identity). Week one: assign Require a tag on resource groups with tagName set to cost-centre and enforcement mode DoNotEnforce, and assign the inherit-tag policy with a system-assigned identity. Review the compliance view and tell teams which groups need the tag. Week two: switch the first assignment to Default enforcement, then run a remediation task for the inherit policy. Evidence: new untagged groups fail with RequestDisallowedByPolicy and resources show the inherited tag. Rollback: delete the assignments.
SUB=/subscriptions/<subscription-id>
REQ=$(az policy definition list --query "[?displayName=='Require a tag on resource groups'].name | [0]" -o tsv)
INH=$(az policy definition list --query "[?displayName=='Inherit a tag from the resource group if missing'].name | [0]" -o tsv)
az policy assignment create -n require-cc --policy $REQ --scope $SUB \
--params '{"tagName":{"value":"cost-centre"}}' --enforcement-mode DoNotEnforce
az policy assignment create -n inherit-cc --policy $INH --scope $SUB \
--params '{"tagName":{"value":"cost-centre"}}' \
--mi-system-assigned --location westeurope --identity-scope $SUB --role "Tag Contributor"
az policy remediation create -n fix-inherit-cc --policy-assignment inherit-ccA deployment blocked by policy and a lock
An engineer deploys a storage account to eastus and the deployment fails with RequestDisallowedByPolicy. The error names the allowed-locations assignment on the Workloads management group. The engineer changes the template to westeurope and redeploys successfully; no exemption is needed. Later, cleanup of the old test group fails with ScopeLocked: a CanNotDelete lock sits on a shared key vault inside it. After confirming the vault is no longer used, the engineer removes the lock with az lock delete, deletes the group, and records the change in the team log.
Quick reference
- Policy controls what resources look like; RBAC controls who can act; locks stop deletes or changes.
- Start new rules with audit or DoNotEnforce, read compliance, then enforce.
- Evaluation order: Disabled, then Append and Modify, then Deny, then Audit.
- Modify needs an assignment identity and a remediation task for existing resources.
- RequestDisallowedByPolicy = deny policy. ScopeLocked = lock. AuthorizationFailed = RBAC.
- az lock create -n keep -g RG --lock-type CanNotDelete protects a whole resource group.
- Prefer a narrow, expiring policy exemption over loosening an assignment for everyone.
Common mistakes
- Assigning a deny policy at a management group without testing it in audit mode first, and blocking every team's deployments.
- Forgetting that a CanNotDelete lock on a resource also stops its resource group from being deleted.
- Expecting a new assignment to act instantly; it can take a while to take effect and compliance results lag further.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Classify each error and name the first thing you would check: RequestDisallowedByPolicy, ScopeLocked, AuthorizationFailed.
- Exercise 2medium
In your lab group, assign Allowed locations with only westeurope, try to create a storage account in eastus, capture the error, then create it in westeurope. Cleanup: delete the assignment and the group. Allow a few minutes after assigning before testing.
- Exercise 3hard
Protect a lab key vault with a CanNotDelete lock, prove the resource group can no longer be deleted, then remove the lock and clean up. Record the error you see as evidence.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Azure Policy cost money?
- Policy evaluation of Azure resources is free. Some features built on it, such as guest configuration for machines outside Azure, can have charges.
- How long after assigning a policy does it start working?
- Usually within minutes for new requests. The first full compliance scan of existing resources can take longer; az policy state trigger-scan starts one on demand.
- Can a lock stop someone deleting files in a storage account?
- No. Locks apply to management operations on the account, not to the data. Use soft delete, versioning and RBAC data roles to protect blobs.
- Should I use policy or RBAC to stop people creating expensive VM sizes?
- Policy. RBAC decides whether someone may create VMs at all; a policy such as Allowed virtual machine size SKUs decides which sizes are acceptable.