Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 57 ยท Identity and Governance

Azure Policy, Locks and Tags

Govern your Azure estate: policy definitions and effects, initiatives, compliance, resource locks, and a tagging strategy that makes cost reports possible.

Role-based access control decides who may act. It says nothing about what they are allowed to create. A teammate with Contributor on a resource group can legitimately deploy a huge virtual machine in a region your company is not permitted to use, with a public IP address and no tags. Governance tools close that gap by describing the rules for resources themselves.

Azure gives you three everyday governance tools. Azure Policy evaluates resources against rules and can block, report or fix them. Resource locks stop deletes and changes by anyone, including owners. Tags attach labels so you can find, group and bill resources. This lesson covers all three. The real services need a subscription, so their JSON and commands are read-only. The runnable examples are JavaScript stand-ins that evaluate rules the same general way, in simplified form.

What Azure Policy does

A policy definition is a JSON document with a condition and an outcome. The condition (if) inspects the properties of a resource. The outcome (then) is an effect. Policy checks resources when they are created or updated, and also scans existing resources on a regular cycle (roughly daily) plus on demand, so a rule added today also reveals older resources that break it.

Here is a definition that only lets resources live in two regions. It is read-only, because it would change a real subscription:

JSON
{
  "properties": {
    "displayName": "Allowed locations for our company",
    "mode": "Indexed",
    "parameters": {
      "allowedLocations": {
        "type": "Array",
        "metadata": { "displayName": "Allowed locations" }
      }
    },
    "policyRule": {
      "if": {
        "not": {
          "field": "location",
          "in": "[parameters('allowedLocations')]"
        }
      },
      "then": { "effect": "deny" }
    }
  }
}

The parts to notice:

  • mode: Indexed means the rule applies to resource types that support tags and locations. All also covers resource groups and subscriptions.
  • parameters let one definition be reused with different values (the list of regions is chosen at assignment time).
  • if can combine field tests with allOf, anyOf and not. Operators include equals, like, in, contains, exists and more.
  • then.effect is the outcome.

Effects

Effect What happens
Deny The request is rejected before the resource is created or changed
Audit The request succeeds; the resource is marked non-compliant
Append / Modify Properties or tags are added or changed on the request, so the resource ends up compliant
AuditIfNotExists Report when a related resource is missing, for example a VM without a backup extension
DeployIfNotExists Deploy the missing related resource automatically
Disabled The rule is switched off (useful while testing)

A sensible rollout path is Audit first, Deny later. Start with Audit to see what would break, fix or exempt those resources, and only then switch to Deny. Turning on Deny for a busy subscription without looking first stops other people's deployments.

Assigning policy

A definition does nothing until it is assigned to a scope: a management group, subscription or resource group (the same hierarchy as in Role-Based Access Control). Assignments are inherited downwards, and you can exclude specific child scopes. Azure includes hundreds of built-in definitions, so you rarely write one from scratch.

Terminal
# Assign a policy definition to a subscription, filling in its parameter
az policy assignment create \
  --name allowed-locations \
  --display-name "Only EU regions" \
  --policy <definition-name-or-id> \
  --scope /subscriptions/<subscription-id> \
  --params '{ "allowedLocations": { "value": ["westeurope", "northeurope"] } }'

# See which resources are non-compliant
az policy state list --filter "complianceState eq 'NonCompliant'" --output table

An initiative (also called a policy set) bundles many definitions into one unit with one assignment and one compliance score. Industry baselines and the Microsoft security benchmark are shipped as initiatives. The compliance view then shows a percentage of compliant resources per definition, which is the figure auditors like to see.

For the effects that change resources (Modify, DeployIfNotExists) the assignment needs a managed identity with enough rights to make the change; see Managed Identities and Service Principals. Existing resources are fixed through a remediation task; new deployments are fixed automatically.

flowchart LR
    REQ["Create or update request"] --> ARM["Azure Resource Manager"]
    ARM --> EVAL{"Policy evaluation"}
    EVAL -->|"Deny matched"| REJ["Request rejected"]
    EVAL -->|"Compliant, or Audit/Modify"| OK["Resource created"]
    OK --> SCAN["Periodic compliance scan"]
    SCAN --> REP["Compliance report"]

Policy sits in the request path, so a Deny rule stops bad resources before they exist; the scan finds the ones that already exist.

A policy evaluator: a stand-in

The real engine is a service with far more operators and aliases. The stand-in below keeps the essential idea: a rule is a condition tree, each effect has a different consequence, and several policies can apply to the same request. The resources and rules are invented.

JS Evaluate resources against policies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that vm-orphan is rejected for its missing owner tag, but a missing cost center is only fixed. Choosing between Deny and Modify is a design decision: Deny forces people to learn the rule, Modify removes friction for rules that can be automated.

Compliance reporting: a stand-in

Compliance is the share of evaluated resources that pass. The second stand-in computes it per policy from a list of invented resources, the way the compliance dashboard summarizes a scan.

JS Compute a compliance score

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Resource locks

Policy governs what resources look like. A lock protects a resource from being deleted or changed by mistake. There are two levels:

  • CanNotDelete: everyone authorized can read and modify, but nobody can delete.
  • ReadOnly: nobody can modify or delete. This behaves like giving every user the Reader role, and can surprise you: some operations that look like reads (for example listing a storage account's keys) are actually POST requests and are blocked.
Terminal
az lock create --name keep-prod-db --lock-type CanNotDelete \
  --resource-group data --resource-type Microsoft.Sql/servers --resource-name prod-sql

A lock applies to every role, including Owner, and is inherited by child resources. To delete a locked resource you must first remove the lock, which needs its own permission. That extra step is the whole point: it turns a one-click accident into a deliberate two-step action. Locks are not security against an attacker who already holds Owner, because an owner can remove them, but they are excellent protection against honest mistakes. They also interact badly with automation, so remember to remove or plan around them in pipelines that delete and recreate resources.

Tags and a tagging strategy

A tag is a name-value pair on a resource, a resource group or a subscription. Tags drive cost reports (see Pricing, Cost Management and Budgets), ownership searches and automation. Three behaviors catch beginners out:

  1. Tags on a resource group are not inherited by its resources unless you add a policy that copies them (the Modify pattern from the stand-in).
  2. Not every resource type supports tags, and there is a per-resource limit on how many you can add.
  3. Tag names are case-insensitive, but values are case-sensitive in many queries, so Prod and prod become two groups in a report.

A small, enforced set works better than a long, ignored one:

Tag Example Purpose
owner [email protected] Who to ask before deleting
costCenter cc-204 Chargeback and budgets
env prod, test, dev Filter and apply different rules
app shop-web Group everything one system uses

Combine tags with policy: require the tag on resource groups (Deny), copy it to children (Modify), and report the stragglers (Audit). Naming conventions for the resource group itself were covered in Resource Groups and Azure Resource Manager.

Beyond single policies

For a whole landing zone (a pre-governed subscription with networking, policies and roles in place) teams combine policy initiatives, role assignments and templates. Azure Blueprints was Microsoft's packaged answer, but it has been deprecated. The recommended replacements are template specs (versioned, shareable templates) and deployment stacks (a deployment that tracks and can clean up the resources it created), written in Bicep (see Bicep and ARM Templates), together with policy assigned through management groups. Check the current Microsoft guidance before starting a new landing zone design, because this area changes.

Azure Resource Graph and finding orphaned resources

Governance needs an answer to "what do we have?" across hundreds of subscriptions. Listing resources subscription by subscription with az resource list is slow. Azure Resource Graph is a service that indexes your resources and answers questions across all subscriptions you can read in one fast query, using a KQL-style language (see Azure Monitor, Log Analytics and Application Insights for KQL basics). The main table is resources; others include resourcecontainers (subscriptions and groups) and advisorresources. It shows the current state, not history; for who changed what, use the activity log.

Terminal
# The graph extension installs on first use
az graph query -q "resources | summarize count() by type | order by count_ desc | limit 10"

az graph query -q "resources | where tags.env == 'dev' | project name, type, location, resourceGroup"

Orphaned resources

Deleting a VM leaves its disk, network interface and public IP behind (see Virtual Machines). They keep costing money or clutter the estate. Typical queries, read-only here and worth adapting to your environment:

KUSTO
// Unattached managed disks
resources
| where type =~ 'microsoft.compute/disks'
| where isempty(managedBy) and properties.diskState == 'Unattached'
| project name, resourceGroup, sku = sku.name, sizeGb = properties.diskSizeGB

// Network interfaces attached to nothing
resources
| where type =~ 'microsoft.network/networkinterfaces'
| where isnull(properties.virtualMachine) and isnull(properties.privateEndpoint)
| project name, resourceGroup

// Public IP addresses not bound to anything
resources
| where type =~ 'microsoft.network/publicipaddresses'
| where isnull(properties.ipConfiguration) and isnull(properties.natGateway)
| project name, resourceGroup, sku = sku.name

Check before deleting: a disk may be a deliberate backup, and a "detached" NSG might be in use by a template. Tag owners, review the list with them, snapshot disks you are unsure about, and use resource locks on the things you must never lose.

  • Resource providers (Microsoft.Compute, Microsoft.Sql) must be registered per subscription; az provider list --query "[?registrationState=='Registered']" shows what is on.
  • Moving resources: az resource move --destination-group rg-new --ids <resource-ids> moves many (not all) resource types between groups or subscriptions; the resource ID changes, and moving locks the source and target groups for a short time.
  • Activity log: az monitor activity-log list --offset 7d --query "[?operationName.value=='Microsoft.Compute/virtualMachines/delete']" finds who deleted what in the last week.
  • Dashboards: an Azure dashboard tile can show the result of a Resource Graph query, so a "dev VMs older than 30 days" list is always on screen.

Querying an inventory: a stand-in

The stand-in loads a small invented inventory and runs the equivalent of the queries above, plus an owner report.

JS Find orphaned resources in an inventory

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Working with policy definitions and initiatives from scripts

Listing definitions

Azure ships hundreds of built-in policy definitions and initiatives (called policy sets). Count and inspect them with Azure PowerShell, or with the CLI, which is easier to filter. These commands only read data:

POWERSHELL
(Get-AzPolicyDefinition).Count          # how many definitions you can see
(Get-AzPolicySetDefinition).Count       # how many initiatives
Get-AzPolicyStateSummary                # compliance counts for the current subscription
Terminal
az policy definition list --query "[?policyType=='BuiltIn'].displayName" -o tsv | head
az policy set-definition list --query "[].displayName" -o table

Building a custom initiative from a list

An initiative is a JSON document that references definitions by ID. When you want to group, say, thirty definitions you already picked, you can generate that JSON from a CSV file of policy IDs instead of clicking them in one by one: read each row, wrap it as { "policyDefinitionId": "...", "parameters": {...} }, and paste the array into the initiative's definition (or pass it to az policy set-definition create --definitions file.json). The stand-in does the conversion step.

JS CSV of policy IDs to initiative JSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Create the initiative once, assign it at a management group, and review compliance as described above. You can also keep policy files in a Git repository and deploy them from a pipeline: export existing policies as JSON, commit them, and let an Azure DevOps or GitHub Actions workflow apply changes after a pull request review (see CI/CD Pipelines). That gives policy the same history and approval trail as application code.

Resource providers

Every Azure service lives in a resource provider namespace such as Microsoft.Compute or Microsoft.DataLakeStore. A subscription must have the provider registered before you can create that kind of resource. Provider states are NotRegistered, Registering and Registered. If a deployment fails with "the subscription is not registered to use namespace", register it:

Terminal
az provider list --query "[?registrationState=='NotRegistered'].namespace" -o tsv | head
az provider register --namespace Microsoft.DataLakeStore
az provider show --namespace Microsoft.DataLakeStore --query registrationState

Registration needs permission at the subscription level, so it is usually done once by an administrator.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the safest way to introduce a new restrictive rule in a busy subscription?

    Audit shows what would be blocked without breaking deployments. After fixing or excluding those resources you can enforce with Deny.
  2. 2. What is the difference between Azure RBAC and Azure Policy?

    A person can have permission to create a VM under RBAC and still be blocked by a policy that forbids that region or size.
  3. 3. Which lock level lets users modify a resource but not delete it?

    CanNotDelete blocks deletion only. ReadOnly blocks modification and deletion alike.
  4. 4. You tag a resource group with costCenter=cc-204. Do its resources get that tag automatically?

    Tags are not inherited by default. A Modify policy can copy the tag from the resource group to its resources.
  5. 5. Why should a Modify or DeployIfNotExists assignment have a managed identity?

    These effects write to resources, so the assignment runs as an identity with a role that permits those writes.

Summary

  • Azure Policy evaluates resources against rules; RBAC decides who may act, Policy decides what may exist.
  • Effects range from Audit (report) to Deny (block) and Modify or DeployIfNotExists (fix); roll out with Audit before Deny.
  • Definitions are assigned to a scope and inherited downward; initiatives bundle many definitions and produce a compliance score.
  • Locks (CanNotDelete, ReadOnly) protect against accidents, even from owners, but are not a defense against a malicious owner.
  • Tags are not inherited by default; keep a small enforced set (owner, costCenter, env, app).
  • Blueprints are deprecated; use template specs, deployment stacks and policy on management groups instead.

Next: Virtual Machines.