Lesson 05 — Resource Locks, Tags & Cost Management

Domain 1 — Identity & Governance AZ-104: 20–25% ~25 min Prereq: Lesson 04 — Azure Policy

Why This Matters in Production

Every Azure administrator has a story about a production resource being accidentally deleted. Resource locks exist specifically to prevent that story from being yours. But locks are a blunt instrument with real operational side effects — applying the wrong lock type to the wrong resource breaks applications in subtle ways that can take hours to debug.

Tags are the foundation of every cost allocation model and almost every automation script in a mature Azure environment. Without them, you are flying blind on spend and you cannot run targeted runbooks. With them, and with governance policy enforcing them, you have the data layer that cost and operations teams depend on.

Cost Management closes the loop: knowing how to read costs, set budgets, interpret Advisor recommendations, and choose between Reserved Instances and Savings Plans is a recurring topic in every enterprise Azure role — and in the AZ-104 exam.

Resource Locks

A resource lock is a control-plane protection layer that operates independently of RBAC. Even a user with the Owner role cannot delete or modify a locked resource unless they first remove the lock — and removing the lock itself requires specific roles.

The Two Lock Types

Lock TypeReadModifyDelete
CanNotDelete ✓ Allowed ✓ Allowed ✗ Blocked
ReadOnly ✓ Allowed ✗ Blocked ✗ Blocked
ReadOnly on certain resources breaks applications ReadOnly on a Storage Account prevents listing storage access keys. Listing keys is a POST operation on the management plane — and ReadOnly blocks all write-class management operations, not just data writes. Any application using key-based authentication will fail immediately. Similarly: ReadOnly on an App Service Plan prevents scaling, and ReadOnly on a Virtual Network prevents adding subnets.

Lock Inheritance

Locks follow the same downward inheritance model as RBAC and Policy:

📋 Subscription lock → applies to all resource groups and resources └─ 📁 Resource Group lock → applies to all resources inside the RG └─ ⚙️ Resource lock → applies to that single resource only

The effective lock on a resource is the most restrictive lock anywhere in its ancestry. A CanNotDelete on the resource group, combined with a ReadOnly on the resource itself, results in ReadOnly behaviour (both delete and modify blocked).

Who Can Manage Locks

This is an exam-tested fact: only the Owner and User Access Administrator built-in roles have the Microsoft.Authorization/locks/* permission required to create or delete locks. Contributor cannot manage locks — a Contributor can create any resource but cannot protect or unprotect one.

Exam trap: RBAC role vs lock interaction A user with Owner role on a resource group still cannot delete a resource inside it if a CanNotDelete lock is applied — at either the resource group or resource level. The lock check happens before the RBAC check is applied to the destructive operation. The user must first remove the lock (which requires Owner/UAA), then delete the resource.

Platform Operations and Locks

Azure platform background processes — such as Azure Backup writing recovery point metadata, or Azure Site Recovery replicating disk data — are not blocked by resource locks. Platform operations bypass customer-applied locks. This is intentional: you don't want a lock on a VM to prevent Azure Backup from functioning.

Production Lock Pattern

Apply CanNotDelete to all production resource groups and to individual critical resources (Key Vaults, hub VNets, storage accounts hosting application state). This is the minimum recommended posture:

  • Lock the production resource group: blocks accidental deletion of any resource inside it.
  • Lock individual Key Vaults separately: even if the RG lock is removed, the vault stays protected.
  • Avoid ReadOnly in production unless you have tested all management-plane operations against the lock — the side effects are rarely worth it.

Tags

Tags are key-value metadata pairs attached to Azure resources, resource groups, and subscriptions. They are the primary mechanism for cost allocation, automation targeting, security classification, and ITSM integration.

Tag Limits and Constraints

ConstraintValue
Max tags per resource / RG / subscription50
Max key length512 characters (128 for storage accounts)
Max value length256 characters
Case sensitivityKeys are case-insensitive for matching; values preserve case
Classic resourcesDo not support tags
Tags do NOT inherit from resource group to child resources This is the most tested tag fact in AZ-104. If you tag a resource group Environment: Production, resources deployed into that group have zero tags by default. Tags on a resource group are metadata about the group, not inherited properties. Many real deployments have broken cost allocation models because someone assumed inheritance existed.

Enforcing Tag Inheritance with Azure Policy

To propagate tags from a resource group to its resources automatically, assign the Azure Policy built-in: "Inherit a tag from the resource group if missing". This uses the Modify effect, which adds the tag to newly created or updated resources that lack it. Combined with a remediation task, you can backfill existing resources.

Modify vs. DeployIfNotExists The Modify effect changes existing resource properties (like tags) without deploying a new resource. DeployIfNotExists is for creating associated resources (like diagnostic settings). For tag enforcement, always use Modify.

Tag Governance Pattern

A mature tagging governance model uses two policy layers working together:

  1. Deny deployments that lack mandatory tags (e.g. CostCenter, Environment, Owner). This enforces tags at creation time.
  2. Modify to auto-apply tags where the value can be inferred (e.g. inherit Environment from the resource group). This reduces friction for developers.

Common mandatory tags in enterprise environments:

TagPurposeExample values
CostCenterFinance billing allocationCC-1042, PLATFORM-ENG
EnvironmentLifecycle and automation targetingprod, staging, dev
OwnerAccountability and incident routingpayments-team@corp.com
DataClassificationSecurity and compliance controlsconfidential, internal, public
AutoShutdownDev/test automation triggertrue, false

Azure Cost Management + Billing

Azure Cost Management is the built-in FinOps platform. Every Azure administrator needs to be proficient in it — not just for the exam, but because cost overruns are one of the most common ways an Azure admin's credibility gets damaged with business stakeholders.

Cost Analysis Views

The Cost Analysis blade (under Subscriptions or Resource Groups) offers several pre-built views:

  • Accumulated cost: running total for the billing period — shows your trajectory against budget.
  • Daily cost: day-by-day bar chart — useful for spotting anomalies and identifying when a spike started.
  • Cost by service: breakdown by Azure service type — identifies your biggest spend categories.
  • Cost by tag: requires tags to exist; shows spend per team/project/environment when tags are properly governed.

Budgets and Alerts

A Budget defines a spending limit at a specific scope (subscription, resource group, or management group) and triggers alerts when thresholds are crossed. Budgets do not stop spending — they alert.

Budget propertyDetail
ScopeSubscription, Resource Group, or Management Group
AmountMonthly, quarterly, or annual dollar limit
Alert threshold% of budget (e.g. 80%, 100%, 120%)
Alert type: ActualTriggers when real spend crosses the threshold
Alert type: ForecastTriggers when projected end-of-period spend will cross the threshold — alerts before the fact
Action groupEmail, SMS, webhook, Logic App, or Automation runbook on alert
Forecast alerts are an underused feature Actual-cost alerts fire when the damage is already done. Forecast alerts fire when Azure's spend model predicts you will exceed budget by end of period — giving you time to act. In production, configure both: an actual alert at 80% and a forecast alert at 100%.

Azure Advisor Cost Recommendations

Azure Advisor analyses your subscription and produces four categories of recommendations. The Cost category includes:

  • Right-size underutilised VMs: Advisor identifies VMs with low CPU utilisation and recommends a smaller SKU.
  • Delete idle resources: unattached disks, idle public IPs, empty load balancers.
  • Reserved Instance recommendations: based on your 7-day or 30-day usage history, recommends RI purchases with projected savings.
  • Azure Hybrid Benefit eligibility: flags VMs running Windows Server that could be covered by AHUB licences.

Cost Optimisation Tools

Tool / OptionDiscount mechanismCommitmentFlexibility
Reserved Instances (RI) Up to 72% off pay-as-you-go. For VMs, SQL, Cosmos DB, and more. 1-year or 3-year Can exchange or cancel (with fee). Scope: single subscription or shared across EA
Azure Savings Plans Up to 65% off. Commit to an hourly dollar spend on compute — discount applies across VM families, regions, and OS. 1-year or 3-year More flexible than RIs — no commitment to specific VM size/region
Azure Hybrid Benefit (AHUB) Bring your own Windows Server or SQL Server licences with Software Assurance. Up to 85% savings on those licence components. Existing SA licences Apply/remove at any time without VM restart
Dev/Test subscriptions Discounted rates for non-production workloads. No Windows OS licence charges. Must not run production SLAs. None (monthly) Full flexibility — PAYG discounted rates
Spot VMs Up to 90% off. Uses Azure's spare compute capacity. Can be evicted with 30 seconds notice. None For interruptible, fault-tolerant workloads only
RI vs. Savings Plan: which to choose? For a stable, predictable workload running a fixed VM SKU in a fixed region for 3 years, a 3-year Reserved Instance gives the maximum discount (up to 72%). Savings Plans offer less maximum discount but reward you with flexibility across compute types — better for organisations still migrating or running diverse compute. RIs are the right answer for the exam when the scenario describes known, committed, long-running workloads.

Check Your Understanding

Click any option to see immediate feedback. Answers represent correct behaviour in a real Azure environment.

1. You apply a ReadOnly lock to a storage account. A developer tries to list the storage account access keys via the portal. What happens?

Listing storage account access keys uses a POST request to the management plane (listKeys action). ReadOnly locks block all management-plane operations that are classified as write or action — not just deletes. This breaks any application or operator task that relies on key authentication. It's one of the most dangerous ReadOnly lock side effects.

2. A resource group has a CanNotDelete lock. An operator with Owner role tries to delete a virtual machine inside it. What is the result?

Lock inheritance means a CanNotDelete lock on a resource group protects every resource inside it, including all VMs, storage accounts, and NICs. No RBAC role — not even Owner — can override a resource lock. The operator must first remove the lock (which requires Owner or User Access Administrator), and then delete the VM.

3. A resource group is tagged with Environment: Production. You deploy a new storage account into it. What tags does the storage account have?

Tags on a resource group are metadata about the group itself — they do not flow down to child resources. This is a deliberate Azure design decision. To enforce tag inheritance, you need an Azure Policy assignment using the built-in "Inherit a tag from the resource group if missing" definition with the Modify effect.

4. You need to alert your finance team when subscription spend reaches 80% of the monthly $10,000 budget before the month ends. What feature implements this?

Budgets in Azure Cost Management are the correct tool. You set a budget amount ($10,000), configure an alert threshold (80%), choose alert type (Actual), and attach an action group with the finance team's email addresses. Azure Monitor metric alerts do not surface billing cost as a native metric — Cost Management budgets are the dedicated billing alert mechanism.

5. Your company runs 20 VMs continuously with fixed SKUs for 3 years. What pricing option gives the maximum discount compared to pay-as-you-go?

For a stable, fixed, committed workload (same VM SKU, same region, 3 years), a 3-year Reserved Instance is the highest-discount option — up to 72% off PAYG rates. Azure Savings Plans are more flexible but cap at around 65% for compute. The scenario is specifically designed to match the RI use case.

6. A Deny policy requires a CostCenter tag on all deployments. A developer needs a temporary exception for sandbox testing. What is the proper governance mechanism?

Azure Policy Exemptions are the correct mechanism for granting scoped, time-limited exceptions to policy assignments. A Waiver exemption acknowledges the resource is non-compliant but provides a justified exception. The exemption scope is limited to the sandbox resource group, it has an expiry date, and it preserves an audit trail — none of which apply to disabling or modifying the policy.
Questions for your teacher (the AI agent)
This lesson covered the operational mechanics of locks, tags, and cost tools. Go deeper on:
  • Walk me through the exact steps to apply a CanNotDelete lock to an entire subscription via Azure CLI.
  • How do I implement a full tagging governance policy initiative with Deny and Modify effects?
  • What is the difference between a Waiver and a Mitigated policy exemption category?
  • How does RI scope work — when would I use shared scope vs. single subscription scope?
  • Can Azure Automation runbooks automatically delete resources when a budget alert fires?
Coming up: Lesson 06 — Storage Accounts: Configuration & Redundancy Governance done, we shift into Domain 2 — Storage. Storage accounts are Azure's foundational data layer. The next lesson covers every redundancy option (LRS through RA-GZRS), access tiers, security configuration, and what happens to replication state after a manual failover. The redundancy comparison table alone is worth memorising before the exam.