Azure Landing Zone Hour 6: Automation — IaC Accelerator, Subscription Vending and Policy as Code
full mode deletes policy resources that are not defined in the repository. Using it by mistake in a shared tenant amounts to a large-scale deletion.- Following Phases 0–3, run one complete ALZ IaC Accelerator bootstrap. Explain every kind of object Bootstrap creates in Azure and in VCS (repositories, template repository, environments, two UAMIs, federated credentials, state storage, and optionally runners and private networking), and clean them up.
- Read the Terraform starter code: the library references in the
alzprovider,policy_default_values/policy_assignments_to_modify/subscription_placementinavm-ptn-alz, and why the root module must pin azurerm~> 4.0. - Read the Bicep (AVM) starter code and the deployment stacks:
actionOnUnmanage,denySettingsMode, exclusion principals, and what happens when you delete a resource from the template. - Design the platform pipeline: plan on PR, approved apply after merge, the plan file as an artifact, and OIDC subjects bound to environments and reusable workflows (details link to GitHub and Azure DevOps hour 3 rather than repeating them).
- Implement subscription vending: one request file → PR validation → approval → subscription alias → placement in a management group → spoke VNet peered with the hub → deployment identity → budget. Know how to “roll forward” when a step fails.
- Manage policy definitions, policy sets, assignments and exemptions with Enterprise Policy as Code (EPAC): the two-stage plan and deploy flow,
fullvsownedOnly, drift and ownership. Also upgrade by the library's calendar version, and migrate from caf-enterprise-scale or the classic ALZ-Bicep.
1-hour timetable
| # | Time | Module | Core content | Animation / interaction | Lab (sandbox tenant) |
|---|---|---|---|---|---|
| 0 | Before class | Setup: platform repositories, deployment identities and state storage | Tool versions, permissions, subscription mapping, single-subscription fallback, costs | Environment self-check checklist | Install the ALZ and EPAC modules, create the lab state storage |
| 1 | 00–06 | ALZ IaC Accelerator end to end | Four phases, inputs.yaml decisions, Bootstrap outputs, Run, cleanup | Bootstrap replay: creating each item in Azure and in VCS | Bootstrap in local file system mode (plan only) |
| 2 | 06–13 | Terraform: avm-ptn-alz and the alz provider | Starter code structure, library references, default values and overrides, subscription placement, dependencies and retries | Plan resolution pipeline: library → resource graph → deployment order | Custom library + modified assignments + plan |
| 3 | 13–21 | Bicep: AVM modules and deployment stacks | alz-bicep-accelerator structure, avm/ptn/alz/empty, deployment stacks, deny settings | Deployment stack simulator: delete a resource / change the template / deny settings | Subscription-scoped stack + denyDelete |
| 4 | 21–28 | Platform pipelines: GitHub Actions and Azure Pipelines | 01 CI / 02 CD, template repository, environment approvals, plan artifacts, drift detection | Pipeline gates and token exchange (including failure injection) | Add scheduled drift detection |
| 5 | 28–35 | Subscription Vending | CAF vending flow, subscription alias, module inputs, permissions, failure and rollback | Core animation: one vending request from PR to a usable new subscription | Vend an existing subscription as the myapp-dev Landing Zone |
| 6 | 35–42 | Policy as Code: EPAC and the policy lifecycle | Desired state, pacEnvironments, the three steps of plan / deploy / roles, exemptions as code, ALZ sync | EPAC planner: the difference between full and ownedOnly | Assignments and exemptions on the epac-dev management group |
| 7 | 42–50 | Version upgrades and policy refresh | Library calendar versions, upgrade process, deprecation and replacement, migration from caf-enterprise-scale / ALZ-Bicep | Upgrade impact analyzer | Library 2026.10.0 → 2026.11.0 walkthrough |
| 8 | 50–60 | Recap of the first six hours, self-check and cleanup | Six-hour knowledge map, self-check, interactive troubleshooting tree, full cleanup | Capability self-check radar + troubleshooting tree | Cleanup script (PlanMode first) |
| — | After class | Cheat sheet · Capstone lab | Deliver a minimal “platform as code” loop for Northwind Maple | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / resources | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| IaC Accelerator bootstrap and cleanup | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | Deploy-Accelerator, Remove-PlatformLandingZone | Local-mode bootstrap |
| Terraform avm-ptn-alz / alz provider | ✓ | ✓ | · | ✓ | ✓ | · | ✓ | ✓ | terraform plan, library_references | Custom library plan |
| Bicep AVM and deployment stacks | ✓ | · | ✓ | ✓ | ✓ | · | ✓ | ✓ | az stack mg|sub create | denyDelete stack |
| Platform pipelines and OIDC | ✓ | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | GitHub environments, ADO checks | Drift detection |
| Subscription vending | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | az account alias, avm-ptn-alz-sub-vending | myapp-dev vending |
| EPAC policy as code | · | · | · | ✓ | · | ✓ | ✓ | ✓ | Build-DeploymentPlans, Deploy-PolicyPlan | epac-dev |
| Version upgrades and migration | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | git diff platform/alz/…, import blocks | Library upgrade walkthrough |
| Troubleshooting automation | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | AADSTS70021, AuthorizationFailed, InvalidPolicyParameterUpdate | Troubleshooting tree |
What this hour leaves out (and where to learn it)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| Deployment options comparison, four-phase overview, minimal Terraform usage | Covered in hour 1; this hour builds on it hands-on | Hour 1 Module 6 |
| ALZ library directory structure, archetypes and architectures, placeholder substitution | Covered in hour 2; this hour only uses “modify” and “upgrade” | Hour 2 Module 6 |
| Role design for the platform plan / apply identities, hard rules for federated credentials | Covered in hour 3; this hour reuses it directly | Hour 3 Module 6 |
Step-by-step OIDC setup: the workflow permissions: id-token: write, service connections | Topic from hour 3 of the CI course | GitHub hour 3 · OIDC · Azure DevOps hour 3 · service connections |
The Terraform language itself: remote state, moved / import, testing, Terraform Policy | Terraform course | Terraform hour 3 · azurerm backend · Hour 2 · refactoring · Hour 5 · policy as code |
Log Analytics workspace, AMA / DCR and other resources that policy_default_values needs | Belongs to management and monitoring | Hour 5 |
| Migrating existing environments in, deep dive into policy troubleshooting | Belongs to operations | Hour 7 |
How to use this course material
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. The vending pipeline animation in Module 5 is the core of this hour; the deployment stack simulator in Module 3 and the EPAC planner in Module 6 are the ones most worth replaying.
A module counts toward progress when you score ≥ 70% on its quiz or click “Mark this module complete”. Progress is saved in this browser's localStorage (if local storage is disabled, it is cleared on refresh).
The “Voice” tab uses the browser's built-in Web Speech API (en-US) to read the narration aloud. If no English voice pack is installed, the narration text can still be read, or passed to a TTS tool.
use_self_hosted_runners and use_private_networking to false. ② If you actually apply the starter code in Phase 3, it deploys the hub network, Azure Firewall, Log Analytics and so on; for those costs, see Hours 4 and 5. The lab in this hour only runs as far as plan. ③ Creating real subscriptions in vending requires an EA / MCA / MPA billing account. Subscriptions themselves are free, but do not forget to cancel them. For amounts, the Azure pricing calculator is the reference.Azure/avm-ptn-alz/azurerm 0.23.0 (released 2026-11-18), Azure/alz provider 0.22.1, ALZ library platform/alz/2026.11.0, Terraform starter code alz-terraform-accelerator v17.7.0, Bicep starter code alz-bicep-accelerator v2.5.0, ALZ PowerShell module 7.1.5, Azure/avm-ptn-alz-sub-vending/azure 0.3.4, Bicep avm/ptn/lz/sub-vending 0.8.0, EPAC 11.5.12. Management group IDs use the ALZ defaults (alz → platform / landingzones …), consistent with hour 1. None of the cloud commands were run against a real tenant; the output is illustrative.Module 0 · Setup: platform repositories, deployment identities and state storage (complete before class)
- A dedicated sandbox Entra tenant where you can use “elevate access” to get User Access Administrator on the root management group
/, and then assign yourself the Owner role on the tenant root management group. (The Accelerator requires Owner on the parent management group; the Bicep path also requires User Access Administrator on/.) - Ideal subscriptions:
sub-alz-management,sub-alz-connectivity,sub-alz-identity(optionalsub-alz-security), and an application subscriptionsub-lz-corp-myapp. The Accelerator officially requires two platform subscriptions, Management and Connectivity (at least 2 for SMB), and strongly recommends 4. - Local tools: PowerShell 7.4+ (the Accelerator must run in pwsh; Cloud Shell and corporate proxies are not supported), Azure CLI 2.61+ (deployment stacks need ≥ 2.61.0; the Accelerator requires ≥ 2.55.0), Git, Terraform 1.12 or later (avm-ptn-alz 0.23.0 requires
>= 1.12), Bicep CLI, VS Code; optionally the GitHub CLIgh. - VCS: a GitHub organization that can create repositories (it needs two PATs: one for Bootstrap and one for runner registration), or an Azure DevOps organization and PAT. If you have neither, that is fine: this hour's lab uses local (local file system) mode by default.
Connection to earlier hours
| From | Reused in this hour | What if I don't have it |
|---|---|---|
| Hour 1 Module 6 | Deployment options and the four-phase concept, the ~/alz-lab/tf-alz starter project | The command page in Module 2 gives the full starter code |
| Hour 2 Module 6 | Library structure, policy_default_values, how to write archetype overrides | The principles page in Module 2 gives a review that is good enough |
| Hour 3 Module 6 | id-alz-platform-plan / id-alz-platform-apply (rg-alz-mgmt-cc) and their federated credentials and roles | The Accelerator creates equivalent identities automatically (with different names; see Module 1). For a hand-built pipeline lab, you can create them with the commands from hour 3 |
| Hour 4 | vnet-hub-cc (10.0.0.0/16), used for hub peering during vending | For the Module 5 lab you can turn off hub_peering_enabled and create only the spoke |
| Hour 5 | The resource ID of law-alz-mgmt-cc, filled into policy_default_values.log_analytics_workspace_id | Use a placeholder ID and run plan only; or create a workspace as in hour 5 (billed per GB) |
Step 1: set the shared variables (both Bash and pwsh versions)
# Bash TENANT_ID=$(az account show --query tenantId -o tsv) SUB_MGMT=<management-subscription-id> SUB_CONN=<connectivity-subscription-id> SUB_APP=<corp-landing-zone-subscription-id> LOC=canadacentral RG_IAC=rg-alz-iac-cc # State storage and identities for the manual lab in this hour ST_IAC=stalziaccc$RANDOM # Storage account name: 3–24 lowercase letters and digits, globally unique TAGS="env=lab owner=platform-team costCenter=cc-1000 workload=alz-iac"
# PowerShell 7.4+ $PSVersionTable.PSVersion # Must be ≥ 7.4 $TenantId = (az account show --query tenantId -o tsv) $Loc = "canadacentral" $Target = "~/accelerator" # Target folder for the Accelerator (config/ and output/)
Step 2: install or update the three PowerShell modules
# ALZ (IaC Accelerator): the officially recommended install / update pattern
$alzModule = Get-InstalledPSResource -Name ALZ 2>$null
if (-not $alzModule) { Install-PSResource -Name ALZ } else { Update-PSResource -Name ALZ }
# EPAC (Module 6) and YAML parsing (the Accelerator tries to install powershell-yaml automatically)
Install-PSResource -Name EnterprisePolicyAsCode
Install-PSResource -Name powershell-yaml
Get-InstalledPSResource -Name ALZ, EnterprisePolicyAsCode | Select-Object Name, Version
Name Version ---- ------- ALZ 7.1.5 EnterprisePolicyAsCode 11.5.12
Step 3: prepare Terraform state storage for the manual labs
The Accelerator creates its own state storage. The rg-alz-iac-cc here is only for the manual labs in Modules 2, 5 and 7, so that state does not stay on your laptop. The storage account has shared key access disabled and uses only Entra authentication (consistent with the remote state section of the Terraform course).
az account set -s $SUB_MGMT az group create -n $RG_IAC -l $LOC --tags $TAGS az storage account create -g $RG_IAC -n $ST_IAC -l $LOC --sku Standard_LRS \ --min-tls-version TLS1_2 --allow-blob-public-access false --allow-shared-key-access false # First give yourself a data-plane role (--auth-mode login depends on it; later also give one to each of the hour 3 plan / apply identities) az role assignment create --assignee $(az ad signed-in-user show --query id -o tsv) \ --role "Storage Blob Data Contributor" \ --scope $(az storage account show -g $RG_IAC -n $ST_IAC --query id -o tsv) sleep 60 # RBAC takes time to take effect for c in tfstate-platform tfstate-vending; do az storage container create --account-name $ST_IAC -n $c --auth-mode login done
{ "principalType": "User", "roleDefinitionId": "/subscriptions/…/providers/Microsoft.Authorization/roleDefinitions/ba92f5b4-2d11-453d-a403-e96b0029c9fe", "scope": "/subscriptions/…/resourceGroups/rg-alz-iac-cc/providers/Microsoft.Storage/storageAccounts/stalziaccc12345" }
{ "created": true }
{ "created": true }
management and then connectivity, and the result depends on whoever wrote last. The other modules can all be completed in a single subscription: Module 2 is plan only; the Module 3 deployment stack is subscription-scoped; Module 5 vends in “existing subscription” mode (subscription_alias_enabled = false); the Module 6 EPAC uses a separate epac-dev management group, and you can temporarily place the single subscription in it.Cost budget (estimate for completing all the labs)
| Resource | Billing model | Usage in this hour | Estimate |
|---|---|---|---|
| Management groups, policies, roles, UAMIs, federated credentials, deployment stacks | Free | — | 0 |
State storage accounts (the Bootstrap one and rg-alz-iac-cc) | Per GB + transactions | A few MB | < US$0.10 |
| Self-hosted runner (ACI) + NAT gateway + public IP | Hourly | Turned off in the lab | 0 (several dollars per day if enabled) |
| Spoke VNet and peering in the vending lab | Peering per traffic | Almost no traffic | < US$0.10 |
| Budget (Cost Management budget) | Free | 1 | 0 |
Self-check list
az role assignment list --assignee $(az ad signed-in-user show --query id -o tsv) \ --scope /providers/Microsoft.Management/managementGroups/$TENANT_ID --query "[].roleDefinitionName" -o tsv terraform version; bicep --version; az version --query '"azure-cli"'
Module 1 · ALZ IaC Accelerator end to end
- For each of Phases 0–3, list the inputs and outputs:
inputs.yaml, the platform configuration file (platform-landing-zone.tfvars/.yaml), thelibfolder, and theoutputfolder. - Name the objects Bootstrap creates in Azure (the intermediate root management group, subscription placement, resource provider registration, state storage, the plan and apply UAMIs with their federated credentials, role assignments, and optional runners and private networking), and the objects it creates in GitHub / Azure DevOps (main repository, template repository, environments, approval teams, branch protection, pipelines).
- Distinguish interactive mode from advanced mode (
New-AcceleratorFolderStructure+Deploy-Accelerator -inputs … -output …), and know the nine Terraform scenario numbers. - Handle cleanup with
Remove-PlatformLandingZone(run-PlanModefirst) andDeploy-Accelerator -Destroy. Know that Bootstrap currently does not support upgrades.
What: the Accelerator is made up of four independently released components
| Component | Repository / package | Version as of 2026-11-18 | Role |
|---|---|---|---|
| ALZ PowerShell module | PowerShell Gallery ALZ (Azure/ALZ-PowerShell-Module) | 7.1.5 (2026-08-28) | Entry-point commands Deploy-Accelerator, New-AcceleratorFolderStructure, Remove-PlatformLandingZone, Grant-SubscriptionCreatorRole |
| Bootstrap module | Azure/accelerator-bootstrap-modules | v7.3.2 (2026-10-10) | One Terraform configuration that creates the continuous delivery environment in Azure and VCS (three variants: alz/github, alz/azuredevops, alz/local) |
| Terraform starter code | Azure/alz-terraform-accelerator (templates/platform_landing_zone) | v17.7.0 (2026-11-06) | Composes the avm-ptn-alz, avm-ptn-alz-management, and hub-spoke or vWAN connectivity modules, and is copied into your repository |
| Bicep starter code | Azure/alz-bicep-accelerator (templates/) | v2.5.0 (2026-11-06) | One Bicep module per management group, plus logging and networking templates, copied into your repository |
When you run Deploy-Accelerator, the ALZ module downloads the matching Bootstrap and starter code versions, renders your inputs into Terraform variables, and runs Terraform once on your machine (which is why you need Azure CLI sign-in and Owner permission). The output is a repository that can deploy itself. From then on, every platform change should happen in that repository as a PR.
Phase 0–3 from a hands-on perspective
| Phase | Decision / action you take | File it lands in |
|---|---|---|
| Phase 0 Planning | IaC (bicep / terraform), VCS (github / azure-devops / local), Bootstrap region, parent management group (blank = tenant root), platform subscription IDs, Bootstrap subscription, naming (service_name defaults to alz, environment_name defaults to mgmt, postfix_number), whether to use self-hosted runners and private networking, approvers | config/inputs.yaml (organized by the “Decision 1–11” comments) |
| Phase 1 prerequisites | pwsh 7.4+, Azure CLI, Git; platform subscriptions; Owner on the parent management group + Owner on each subscription (Bicep also needs UAA on /); PATs for VCS | — |
| Phase 2 Bootstrap | Run the wizard or the advanced commands; edit the platform configuration file: starter_locations (replace placeholders such as <region-1>); for Terraform, also fill in defender_email_security_contact; enter yes and press Enter after the plan | config/platform-landing-zone.tfvars (Terraform) or config/platform-landing-zone.yaml (Bicep); Terraform also has config/lib/ |
| Phase 3 Run | Run the “02 Azure Landing Zones Continuous Delivery” pipeline: plan first, then apply after approval; in local mode, run ./scripts/deploy-local.ps1 | The generated repository / output/ folder |
Why: why you “bootstrap” instead of writing the pipeline directly
- Chicken-and-egg problem: the platform pipeline needs identities, state storage, environment approvals and federated credentials, and these are infrastructure too. Bootstrap uses your own permissions to create them all once. After that, people step out and the pipeline takes over.
- Least-privilege defaults: the plan identity has only Reader on the intermediate root (Terraform also adds Storage Blob Data Contributor on the state container), and the apply identity gets Owner but can only obtain a token from the protected apply environment (analyzed in hour 3).
- Tamper-resistant pipeline: the GitHub variant creates two repositories. The main repository
alz-mgmtholds only IaC and the caller workflows. The reusable workflows that actually run plan / apply live in the template repositoryalz-mgmt-templates. The OIDC subject is customized to includerepository,environmentandjob_workflow_ref, so even if someone changes a workflow in the main repository, they cannot obtain a token for the apply identity.
How: the objects Bootstrap actually creates (GitHub variant, default names)
| Location | Object | Default name (service=alz, env=mgmt, postfix=1, region canadacentral) |
|---|---|---|
| Azure · management groups | Intermediate root management group (when not Classic) + moves the platform subscriptions under it | IDs and display names come from the starter configuration; defaults are alz / “Azure Landing Zones” |
| Azure · resource groups | State, identity; optionally agents, network | rg-alz-mgmt-state-canadacentral-1, rg-alz-mgmt-identity-canadacentral-1 |
| Azure · identity | Two UAMIs + a federated credential per environment | id-alz-mgmt-canadacentral-plan-1, id-alz-mgmt-canadacentral-apply-1 |
| Azure · state | Storage account + container (Terraform) | Form stoalzmgmtcac1xxx (includes a random string), container mgmt-tfstate |
| Azure · roles | Intermediate root: plan=Reader, apply=Owner; state container: Storage Blob Data Contributor for both; Bicep's What-If identity also has a custom role containing deployments/whatIf/action | — |
| Azure · optional | Self-hosted runner (ACI), container registry, VNet (default 10.0.0.0/24), NAT gateway, public IP, private endpoint | aci-alz-mgmt-…, vnet-alz-mgmt-… |
| GitHub | Main repository, template repository, environments plan / apply, approval team, runner group, branch protection, Actions variables | alz-mgmt, alz-mgmt-templates, alz-mgmt-plan, alz-mgmt-apply, alz-mgmt-approvers |
| Azure DevOps | Within the project: repositories, environments, approval checks, workload identity federated service connections, variable groups, pipelines (names start with 01 / 02) | Also based on service_name and environment_name |
Note: the course naming in hour 3 (id-alz-platform-plan / -apply) differs from the Accelerator's default names. When you use the Accelerator, the names it generates are the ones to use. You can also override the templates in inputs.yaml with resource_names (placeholders such as {{service_name}}, {{environment_name}}, {{azure_location}}, and {{postfix_number}} are supported).
When: which mode to choose, and which scenario
- Interactive mode:
Deploy-Acceleratorwith no parameters. The wizard fills ininputs.yaml, which suits a first run. Advanced mode:New-AcceleratorFolderStructure -iacType terraform -versionControl github -scenarioNumber 1 -targetFolderPath ~/acceleratorgenerates the folder structure, and then you run it with-inputs,-starterAdditionalFilesand-output. This suits keeping the configuration in version control and running it repeatedly. - Terraform scenario numbers (the advanced mode docs say “1–9”): multi-region / single-region × hub-spoke / vWAN × Azure Firewall / NVA, plus a management-only scenario and an SMB single-region scenario. For the mapping between numbers and scenarios, the official Scenarios page is authoritative. Bicep does not use scenario numbers.
- Local mode: if you do not want to authorize Bootstrap to access your company's GitHub / ADO, use it first to generate the code and
deploy-local.ps1, then connect the output to a custom VCS later.
- “If I change inputs.yaml and rerun Bootstrap, I can upgrade.” The official FAQ is explicit: Bootstrap is a one-time operation and does not currently support upgrades. What you upgrade is the starter code and module versions in the repository (Module 7).
- “Bootstrap deploys the hub network and firewall.” It does not. It only creates the continuous delivery environment. The hub, Log Analytics and similar resources are created when the Phase 3 pipeline applies the starter code.
- “The Terraform starter code can use azurerm 5.x directly.” It cannot: the official guidance is to keep the root module on
~> 4.0, and with 5.x,terraform initfails. - “Cleanup just means deleting the resource group.” A platform landing zone involves management groups, policies, roles and subscription placement. Use
Remove-PlatformLandingZone, and on the VCS side useDeploy-Accelerator -Destroy.
Architecture diagram: after Bootstrap, “two repositories + two identities + one state”
Flow diagram: from configuration to the first apply
Bootstrap replay: creating each item in Azure and in VCS
Choose IaC, VCS and the optional items, then click “Replay”. The left and right columns show the objects Bootstrap creates in Azure and in VCS, and the terminal shows the matching Terraform resource addresses (simplified; actual addresses follow the bootstrap plan). The last two steps simulate the first Phase 3 run.
Core commands
| Command | Purpose | Notes |
|---|---|---|
Deploy-Accelerator | Interactive wizard | Only writes inputs.yaml for you; the platform configuration files still need to be checked by hand |
New-AcceleratorFolderStructure | Generates the config/ folder and example files | Parameters -iacType -versionControl -scenarioNumber -targetFolderPath |
Deploy-Accelerator -inputs … -output … | Run Bootstrap in advanced mode | Terraform also adds -starterAdditionalFiles "<t>/config/lib" |
Remove-PlatformLandingZone | Clean up the Azure part of the platform landing zone | Preview first with -PlanMode |
Deploy-Accelerator -Destroy | Delete the VCS and Azure bootstrap resources created by Bootstrap | Keep the folder structure; if it is lost, use Remove-GitHubAccelerator / Remove-AzureDevOpsAccelerator |
Advanced mode (Terraform + local)
$iacType = "terraform" # or "bicep" $versionControl = "local" # "github" / "azure-devops" / "local" $scenarioNumber = 1 # Terraform 1–9; Bicep ignores it $targetFolderPath = "~/accelerator" New-AcceleratorFolderStructure -iacType $iacType -versionControl $versionControl ` -scenarioNumber $scenarioNumber -targetFolderPath $targetFolderPath code (Resolve-Path "$targetFolderPath/config").Path # Edit inputs.yaml and tfvars az login --tenant "<tenant-id>" --use-device-code az account set --subscription "<bootstrap-subscription-id>" Deploy-Accelerator ` -inputs "$targetFolderPath/config/inputs.yaml", "$targetFolderPath/config/platform-landing-zone.tfvars" ` -starterAdditionalFiles "$targetFolderPath/config/lib" ` -output "$targetFolderPath/output"
Key excerpt from inputs.yaml (GitHub example, from the official examples)
bootstrap_location: "canadacentral" root_parent_management_group_id: "" # empty = tenant root group subscription_ids: management: "<management-subscription-id>" identity: "<identity-subscription-id>" connectivity: "<connectivity-subscription-id>" security: "<security-subscription-id>" bootstrap_subscription_id: "" # empty = current CLI subscription service_name: "alz" environment_name: "mgmt" postfix_number: 1 use_self_hosted_runners: false # off for the lab; on is recommended for production use_private_networking: false github_personal_access_token: "<token-1>" # can also be set with TF_VAR_github_personal_access_token github_runners_personal_access_token: "<token-2>" github_organization_name: "<github-organization>" apply_approvers: ["<email-address>"] iac_type: "terraform" bootstrap_module_name: "alz_github" starter_module_name: "platform_landing_zone"
Plan: 4x to add, 0 to change, 0 to destroy. Do you want to perform these actions? Enter a value: yes Apply complete! Resources: 4x added, 0 changed, 0 destroyed. Outputs: module_output_directory_path = "/home/me/accelerator/output/local-output"
The resource count is illustrative and depends on the VCS type, whether runners are enabled, and so on. How to verify: az identity list -g rg-alz-mgmt-identity-canadacentral-1 -o table should show the plan and apply UAMIs. Common mistakes: running in Windows PowerShell 5.1; forgetting to replace the placeholders in starter_locations.
Lab 1: Bootstrap in local file system mode, plan only (about 15 minutes, almost free)
alz management group by hand in hour 1, change the id of the intermediate root in the alz_custom.alz_architecture_definition file under config/lib/ (YAML or JSON) to alz-acc. Also change the display name, and change the parent_id of the direct child management groups to alz-acc. If subscription_placement / policy_assignments_to_modify in tfvars reference that ID, update them too, so the two implementations do not fight over the same tree.$versionControl = "local" and $scenarioNumber = 1. (If you do not need connectivity resources, you can choose the management-only scenario; the official scenario list is authoritative.)inputs.yaml, set the region to canadacentral and enter the subscription IDs (with a single subscription, use the same ID for management and connectivity). In tfvars, replace every <region-1> with canadacentral and <region-2> with canadaeast, and fill in defender_email_security_contact.Deploy-Accelerator …, read the plan, and confirm it only includes resource groups, identities, storage, roles, management groups and subscription placement. Press Enter to apply.ls ~/accelerator/output/local-output # starter code + scripts/deploy-local.ps1
az identity list --query "[?contains(name,'alz-mgmt')].{name:name,rg:resourceGroup}" -o table
az role assignment list --scope /providers/Microsoft.Management/managementGroups/alz-acc \
--query "[].{who:principalName,role:roleDefinitionName}" -o table
Name Rg ------------------------------------ ----------------------------------- id-alz-mgmt-canadacentral-plan-1 rg-alz-mgmt-identity-canadacentral-1 id-alz-mgmt-canadacentral-apply-1 rg-alz-mgmt-identity-canadacentral-1 Who Role ------------------------------------ ------ <plan-uami-object-id> Reader <apply-uami-object-id> Owner
scripts/deploy-local.ps1 and read what it does, then run it. When the plan appears, type no (do not deploy the hub and firewall). Note the resource count in the plan; Module 2 uses it.Remove-PlatformLandingZone … -PlanMode before running them.Case 1: someone edits a workflow directly in the main repository after Bootstrap
Problem: to “speed things up”, an engineer created a new workflow in alz-mgmt that calls terraform apply directly and references the apply environment. The OIDC exchange failed (AADSTS70021). Cause: Bootstrap customized the OIDC subject to include job_workflow_ref, so only the reusable workflows in the template repository alz-mgmt-templates match the federated credential of the apply identity. Conclusion: this is by design, not a fault. Changes to the pipeline go through a PR in the template repository and are approved by the platform owner.
Case 2: Bootstrap was run with a personal account, and that employee left three months later
Problem: the personal account used for Bootstrap was disabled, and the team worries the pipeline will break. Facts: the pipeline uses UAMIs and federated credentials, which are unrelated to the personal account. However, permissions Bootstrap granted to the personal account (if grant_permissions_to_current_user is at its default) should be reviewed and revoked after Bootstrap. Approach: add “revoke the bootstrapper's permissions” to the post-Bootstrap checklist, and manage platform Owner with PIM, as in hour 3.
Case 3: Bootstrap fails behind a corporate proxy
Problem: running Deploy-Accelerator on the office network, the download of Terraform and the providers times out. Facts: the official prerequisites state that proxies and Cloud Shell are not supported. Approach: run Bootstrap from a jump VM with direct internet access (pwsh 7.4+, Azure CLI, Git). For production pipelines, use private networking and a self-hosted runner, with outbound traffic going through the NAT gateway.
Common errors and fixes
Deploy-Accelerator: The term 'Deploy-Accelerator' is not recognized as a name of a cmdlet
Cause: running in Windows PowerShell 5.1, or the module is not installed. Diagnosis: $PSVersionTable.PSVersion; Get-InstalledPSResource -Name ALZ. Fix: install or update the ALZ module in pwsh 7.4+.
Bootstrap plan fails: …does not have authorization to perform action 'Microsoft.Management/managementGroups/write'…
Cause: the runner is not Owner on the parent management group (by default, the tenant root). Fix: elevate access and grant Owner at the tenant root (revoke it after the lab); or set inputs.yaml to a parent management group where you are Owner. The actual error text is the reference.
No available releases match the given constraints … hashicorp/azurerm
Cause: the root module, or a module you added, requires azurerm 5.x, while the starter code pins ~> 4.0. Fix: keep the root module at ~> 4.0 (the official FAQ states that v5 is not currently supported). Prevention: do not use open constraints such as >= 4.0.
The runner group still has runners in it, so Deploy-Accelerator -Destroy fails to delete the GitHub resources
Cause: a GitHub API limit: a runner group cannot be deleted while runners are still registered to it. Fix: delete the runners manually in the GitHub organization settings first, then run -Destroy again.
Bootstrap succeeds, but the first apply reports AuthorizationFailed (on the newly created management group)
Cause: eventual consistency between a management group and its role assignments. The CD job of the starter code sets AZAPI_RETRY_GET_AFTER_PUT_MAX_TIME=60m and retries AuthorizationFailed on AzAPI resources. Fix: wait a few minutes and run again. Do not respond by granting the apply identity more permissions.
1. Use advanced mode to generate the folder structure for Bicep + Azure DevOps in ~/acc-bicep.
New-AcceleratorFolderStructure -iacType "bicep" -versionControl "azure-devops" ` -scenarioNumber 1 -targetFolderPath "~/acc-bicep" # Bicep ignores the scenario number
2. Preview what cleaning up the platform landing zone would delete (the intermediate root is created under the tenant root, with two platform subscriptions).
Remove-PlatformLandingZone -ManagementGroups "<tenant-root-mg-id>" ` -Subscriptions "<mgmt-sub-id>", "<conn-sub-id>" -PlanMode
The security team does not allow Bootstrap to hold an organization-level GitHub PAT, and does not allow runners to access the public internet. How can you still use the Accelerator?
First use local mode to generate the starter code and bootstrap resources (state storage, UAMIs, roles), and push output to a company-approved repository. Configure environment approvals and federated credentials by hand, following GitHub / ADO hour 3 (the subject bound to the environment, and where needed a reusable workflow with a customized job_workflow_ref). Runners use the company's own private-network runners, and state storage goes through a private endpoint. Trade-off: you lose the VCS consistency that Bootstrap automates, so these manual steps need to be written into a checklist.
Verified video resources
Official documentation
- Azure Landing Zones IaC Accelerator (aka.ms/alz/acc)
- Phase 2 – Bootstrap
- accelerator-bootstrap-modules
- Platform landing zone implementation options
Video storyboard script (about 90 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided for a video tool to produce.
On screen: a terminal where you type Deploy-Accelerator, and the wizard asks each question in turn (IaC, VCS, region, subscriptions).
Narration: Bootstrap runs only once, and uses your permissions to set up the continuous delivery environment.
On screen: on the left, GitHub shows two repositories and two environments; on the right, Azure shows two identities, one storage account and the intermediate root management group.
Narration: the plan identity is read-only, and the apply identity is Owner, but only the approved environment and the template repository's workflows can obtain its token.
On screen: a PR triggers 01 CI and shows the plan; after the merge, 02 CD waits for approval, then applies once approved.
Narration: from this point on, people step out, and every platform change is a PR.
Module 2 · Terraform: avm-ptn-alz and the alz provider
- Read the file layout of the
alz-terraform-acceleratorstarter code:main.management.groups.tf,main.management.resources.tf, two connectivity files,lib/(library metadata, architecture definitions, 12*_customarchetype overrides), andmanagement_group_settingsin tfvars. - Explain the main inputs of avm-ptn-alz 0.23.0:
policy_default_values,policy_assignments_to_modify(newpolicy_definition_idandrole_assignments_enabled),subscription_placementand destroy behavior,management_group_hierarchy_settings,*_dependencies, andretries/timeouts. - Understand where the plan's resources come from: the provider resolves the library → the module generates management groups (by hierarchy), definitions, policy sets, role definitions, assignments, role assignments for policy managed identities, and subscription placement.
- Know that the starter code and module versions can drift apart (starter code v17.7.0 still references avm-ptn-alz 0.21.0), so upgrades are your job (Module 7).
What: the four layers of the starter code
| Layer | Files | Contents | Who changes it |
|---|---|---|---|
| Versions and providers | terraform.tf | Terraform ~> 1.12; alz ~> 0.21; azurerm ~> 4.0; azapi ~> 2.0; provider "alz" { library_overwrite_enabled = true, library_references = [{ custom_url = "${path.root}/lib" }] } | Platform team (when upgrading) |
| Module composition | main.management.groups.tf and so on | module "management_groups" { source = "Azure/avm-ptn-alz/azurerm" … }, the management resources module, and the hub-spoke or vWAN module; the modules are linked together with dependency variables | Rarely changed; compare against the upstream diff when upgrading |
| Library | lib/alz_library_metadata.json, lib/architecture_definitions/alz_custom…, lib/archetype_definitions/*_custom.alz_archetype_override.yaml | The ref for the platform/alz dependency (2026.11.0 in v17.7.0); management group IDs and display names; adding, removing and assigning definitions for each management group | Governance team (often) |
| Configuration | platform-landing-zone.auto.tfvars | starter_locations, custom_replacements (named templates), management_group_settings (defaults, subscription placement, assignment changes), and connectivity and management resource settings | Platform team (often) |
Note one detail: the starter code references the library as a local library plus dependency. The provider only points to ${path.root}/lib, while the dependencies entry in lib/alz_library_metadata.json reads { "path": "platform/alz", "ref": "2026.11.0" }. So a library upgrade changes this JSON, not the provider block. The direct approach in hour 2 (two entries in library_references) is equivalent.
How: key inputs for avm-ptn-alz 0.23.0
| Input | Purpose | Notes |
|---|---|---|
architecture_name / parent_resource_id / location | Choose the architecture definition, the parent of the intermediate root (tenant ID or parent MG name), and the region for the DINE managed identity | The starter code uses alz_custom |
policy_default_values | Fill in parameters for every assignment that references it, by default name (for example log_analytics_workspace_id, private_dns_zone_subscription_id, ama_user_assigned_managed_identity_id) | When you use the module directly, values must be written as jsonencode({ value = … }). The starter code's tfvars use plain strings, which the config-templating submodule converts. |
policy_assignments_to_modify | Change enforcement_mode, parameters, non_compliance_message, resource_selectors, overrides and identity by management group ID and assignment name. | 0.23.0 adds policy_definition_id (points to a definition managed outside the module). 0.22.0 adds role_assignments_enabled. creation_enabled = false only suits very small deployments. The proper approach is an archetype override. |
subscription_placement | { key = { subscription_id, management_group_name } } | Destroy behavior subscription_placement_destroy_behavior: default (tenant default MG) / parent / intermediate_root / custom |
management_group_hierarchy_settings | Default management group and "require authorization for management group creation" | Equivalent to the hierarchy-settings CLI from hour 1. Don't manage it in both places. |
management_groups_dependencies, policy_assignments_dependencies, policy_role_assignments_dependencies | Expresses "create the LAW, DCR and private DNS zones first, then the assignments" | The module does not support depends_on |
management_group_role_assignments | Create role assignments on the specified management group. | The documentation recommends using condition to limit which roles can be granted. |
retries / timeouts / delays | Handling ARM eventual consistency | The default create timeout for policy assignments is 20m; the rest default to 15m. |
Why: why the ALZ Terraform implementation uses AzAPI
- The ARM APIs for management groups, policy and roles change often. AzAPI calls REST API versions directly, so you don't have to wait for azurerm to release new resource types. avm-ptn-alz itself does not depend on azurerm.
- The management and connectivity modules in the starter code still use azurerm 4.x. The official notes say they are planned to move to AzAPI, so azurerm 5.x is not supported for now.
- The alz provider only does "data processing": it downloads the library, merges overrides, replaces placeholders, and computes the roles that policy managed identities need. It manages no resources. It only provides data sources and functions.
When: change tfvars or lib?
| Requirement | Where to change |
|---|---|
| Set the workspace ID and private DNS subscription for DINE assignments | tfvars → policy_default_values |
| Change a default assignment to DoNotEnforce, or change its parameters | tfvars → policy_assignments_to_modify |
| Remove Deploy-Private-DNS-Zones from corp, or add a custom assignment to landing_zones | lib → policy_assignments_to_remove / _to_add in corp_custom / landing_zones_custom |
| Add a prefix to management group IDs, or add or remove management groups | lib → architecture definition (also sync the MG names referenced in tfvars) |
| Upgrade the library | lib → ref in alz_library_metadata.json |
- "The keys of policy_assignments_to_modify are management group display names." No, they are management group IDs (such as
alz,corp). - "Upgrading avm-ptn-alz to 0.23.0 also upgrades the library." No. The library version is set only by
ref. The module and the library are independent. - "To guarantee order, add depends_on to module "management_groups"." Not supported. It turns the data source into a value known only after apply, and plan fails with
Invalid for_each argument. Use*_dependenciesinstead. - "A plan shows an assignment to be replaced (-/+), so someone must have changed it by hand." It could also be a library upgrade that switched the assignment to a new policy set name (with a date suffix). See Module 7.
Data flow: from lib to Azure objects
Dependencies: why DINE assignments wait for management resources
Plan resolution pipeline: library → resource graph → deployment order (with injectable failures)
Choose a configuration and step through what the alz provider and avm-ptn-alz each do during terraform init / plan / apply. "Inject failure" shows at which step four common failures appear and what they report (error text is illustrative; the actual text may differ).
Core commands and configuration
| Command / configuration | Purpose |
|---|---|
terraform init -backend-config=… | Same as the starter code: backend parameters are passed at init time (the pipeline injects them from variables). |
terraform plan -out tfplan / terraform show tfplan | Generate and review the plan. The pipeline passes the plan file to apply as an artifact. |
terraform state list | grep management_groups_level | Confirm management group resource addresses |
jq -r '.dependencies' lib/alz_library_metadata.json | Check the current library version |
1) Without Accelerator, compose the code directly (continuing the ~/alz-lab/tf-alz from Hour 1)
# terraform.tf
terraform {
required_version = ">= 1.12"
required_providers {
alz = { source = "Azure/alz", version = "~> 0.22.1" }
azapi = { source = "Azure/azapi", version = "~> 2.12" }
}
backend "azurerm" {
resource_group_name = "rg-alz-iac-cc"
storage_account_name = "<stalziaccc…>"
container_name = "tfstate-platform"
key = "alz6-governance.tfstate"
use_azuread_auth = true # no storage account key
}
}
provider "alz" {
library_overwrite_enabled = true
library_references = [{ custom_url = "${path.root}/lib" }] # declares the dependency on platform/alz in lib
}
provider "azapi" {}
data "azapi_client_config" "current" {}
# main.tf
module "alz" {
source = "Azure/avm-ptn-alz/azurerm"
version = "0.23.0"
architecture_name = "alz6" # custom architecture in lib/architecture_definitions
parent_resource_id = data.azapi_client_config.current.tenant_id
location = "canadacentral"
policy_default_values = {
log_analytics_workspace_id = jsonencode({ value = "/subscriptions/<mgmt-sub>/resourceGroups/rg-alz-mgmt-cc/providers/Microsoft.OperationalInsights/workspaces/law-alz-mgmt-cc" })
email_security_contact = jsonencode({ value = "secops@example.com" })
}
policy_assignments_to_modify = {
corp6 = {
policy_assignments = {
Deny-Public-Endpoints = { enforcement_mode = "DoNotEnforce" } # observe before enforcing
}
}
}
subscription_placement = {
myapp = { subscription_id = "<app-sub-id>", management_group_name = "corp6" }
}
subscription_placement_destroy_behavior = "intermediate_root" # on destroy, return to alz6, not the tenant root
management_group_hierarchy_settings = {
default_management_group_name = "sandbox6"
require_authorization_for_group_creation = true
}
}
// lib/alz_library_metadata.json
{
"$schema": "https://raw.githubusercontent.com/Azure/Azure-Landing-Zones-Library/main/schemas/library_metadata.json",
"name": "local",
"display_name": "alz6 lab library",
"description": "Lab overrides for hour 6",
"dependencies": [ { "path": "platform/alz", "ref": "2026.11.0" } ]
}
# lib/architecture_definitions/alz6.alz_architecture_definition.yaml (excerpt: copy the alz architecture from the library, then change the IDs)
name: alz6
management_groups:
- id: alz6
display_name: Azure Landing Zones (hour 6)
archetypes: [root]
parent_id: null
exists: false
- id: platform6
display_name: Platform
archetypes: [platform]
parent_id: alz6
exists: false
- id: corp6
display_name: Corp
archetypes: [corp]
parent_id: landingzones6
exists: false
# … the other 9 management groups follow the same pattern, all with the suffix 6
terraform init -upgrade terraform plan -out tfplan | tee plan.txt | tail -3 grep -c 'azapi_resource.management_groups_level' plan.txt grep 'policy_assignments\["corp6/Deny-Public-Endpoints"\]' -A3 plan.txt | grep enforcementMode
Plan: 3xx to add, 0 to change, 0 to destroy.
12
enforcementMode = "DoNotEnforce"
How to verify: 12 management groups, Deny-Public-Endpoints on corp6 is DoNotEnforce, and subscription_placement["myapp"] exists. Common mistakes: writing policy_default_values as a plain string (it should be jsonencode({ value = … })); missing a parent_id change in the architecture file; the same tree is already managed by the hour 1 CLI or Bootstrap. Resource counts and addresses are examples.
Lab 2: plan (optionally apply) a modified governance setup on a separate alz6 tree (about 15 minutes)
cd ~/alz-lab/tf-alz && mkdir -p lib/architecture_definitions git clone -q --depth 1 --branch platform/alz/2026.11.0 https://github.com/Azure/Azure-Landing-Zones-Library.git /tmp/alzlib cp /tmp/alzlib/platform/alz/architecture_definitions/alz.alz_architecture_definition.json lib/architecture_definitions/alz6.alz_architecture_definition.json # Edit: name → alz6; add the suffix 6 to each id and parent_id (alz → alz6, corp → corp6 …)
terraform.tf, main.tf and lib/alz_library_metadata.json. For the workspace ID, use law-alz-mgmt-cc from hour 5. If you don't have it, keep the placeholder ID and only run plan.terraform init should show that azure/alz v0.22.1 is installed; then run terraform plan -out tfplan. Confirm 12 management groups and that Deny-Public-Endpoints is DoNotEnforce.Deploy-Diag-LogsCat (a DINE on root) in the plan, compare it with the assignment file in .alzlib, and confirm that the logAnalytics parameter has been replaced with your workspace ID.terraform apply tfplan (about 10–20 minutes, no cost). Otherwise, stop at plan.terraform destroy. Subscriptions move back to alz6 first under the intermediate_root behavior, then return to the tenant default MG when their management groups are deleted. If you only planned, just delete tfplan.Case 1: after upgrading the starter code, the plan shows 40 role assignment replacements
Problem: after upgrading avm-ptn-alz, the plan shows that every policy managed identity's role assignment must be destroyed and recreated. Cause: the naming of role assignments (deterministic GUIDs versus random UUIDs) changed between versions. The starter code's tfvars provides role_assignment_name_use_random_uuid to keep the old naming. The 0.23.0 notes also mention changes to the lifecycle of random UUIDs. Fix: read the release notes, set this switch as needed to keep the old naming, and apply first in a non-production tenant to confirm there is no brief gap in permissions.
Case 2: DINE assignment created, but remediation fails
Problem: the Deploy-VM-Monitoring assignment was created, but all remediation tasks failed. Cause: the DCR ID in policy_default_values points to a resource that hasn't been created yet. The assignment itself does not check whether the resources in its parameters exist. Fix: use policy_assignments_dependencies to depend on the outputs of the management resource modules. The Accelerator starter code already chains them this way.
Case 3: the governance team wants to maintain its own organization policy
Problem: the governance team is not familiar with Terraform, but needs to add audit-type assignments often. Fix: put the organization's custom definitions and assignments in JSON / YAML under lib/ (they only edit JSON), and attach them to management groups through policy_assignments_to_add in an archetype override. Or hand this part to EPAC (Module 6), and use policy_definition_id so the avm-ptn-alz assignments reference the external definitions. The key is that each assignment has only one owner.
Common errors and fixes
Error: Invalid for_each argument … will be known only after apply (inside module.alz)
Cause: you added depends_on to the module, or passed values into policy_default_values or the modification entries that are only known after apply. Fix: remove depends_on and use *_dependencies instead. Make sure the map keys are literals.
alz provider: library reference platform/alz@2026.13.0 … not found (use the actual error text)
Cause: the library tag does not exist, or the network cannot reach GitHub. Diagnose: git ls-remote --tags https://github.com/Azure/Azure-Landing-Zones-Library.git | grep platform/alz/. Fix: use a tag that exists. In an offline environment, use custom_url to point to an internal mirror.
AuthorizationFailed … 'Microsoft.Authorization/roleAssignments/write' over scope '/providers/Microsoft.Management/managementGroups/alz6'
Cause: the apply identity has only Contributor (which cannot write role assignments), but DINE / Modify assignments need to grant access to a managed identity. Fix: the apply identity needs Owner on the intermediate root (or Contributor plus RBAC Administrator with a condition). This matches hour 3 and the Accelerator defaults.
policy_assignments_to_modify changed, but the plan shows no change
Cause: the key was written as a display name or an old ID (for example corp instead of corp6), or the assignment name is misspelled. Diagnose: grep -l '"name": "Deny-Public-Endpoints"' .alzlib/**/policy_assignments/*, then check which MG the archetype is attached to in the architecture definition. Fix: use the MG ID and the assignment name.
terraform destroy is stuck at subscription placement / management group deletion
Cause: the management group still contains subscriptions outside the module or child MGs, or the destroy behavior moves subscriptions to an MG that doesn't exist. Fix: first move the subscriptions outside the module out of the group; check subscription_placement_destroy_behavior.
1. Find the library version and the avm-ptn-alz version that the starter code currently references.
jq -r '.dependencies[] | "\(.path)@\(.ref)"' lib/alz_library_metadata.json grep -A2 'Azure/avm-ptn-alz/azurerm' main.management.groups.tf | grep version
2. Write a tfvars snippet (in the starter code format) that sets Enable-DDoS-VNET on connectivity to DoNotEnforce.
management_group_settings = {
policy_assignments_to_modify = {
connectivity = {
policy_assignments = {
Enable-DDoS-VNET = { enforcement_mode = "DoNotEnforce" }
}
}
}
}Your company requires that "Deploy-Private-DNS-Zones is not allowed in corp, because DNS is managed by the local team," and that all DINE assignments must use one user-assigned managed identity. How would you implement this in the starter code?
① Add Deploy-Private-DNS-Zones to policy_assignments_to_remove in lib/archetype_definitions/corp_custom.alz_archetype_override.yaml (and decide whether to keep Audit-PeDnsZones for auditing). ② In policy_assignments_to_modify, set identity = "UserAssigned" and identity_ids on the related assignments, and grant the UAMI the required roles in advance (or keep the role assignments the module computes from roleDefinitionIds). ③ In the PR's plan, confirm that corp has one fewer assignment and that the DINE assignments' identity type has changed. ④ Document that this is a deviation from upstream, and review it when you upgrade the library.
Verified videos
Official documentation
- Terraform Registry: avm-ptn-alz
- alz provider documentation
- Terraform starter code: platform_landing_zone
- Terraform starter code options
Video storyboard (about 90 seconds)
This lesson material cannot generate video or MP3 directly. The storyboard and narration script are provided, so you can hand them to a video tool.
Visual: the lib folder and the tfvars file sit side by side, with arrows feeding into a gear labeled alz provider.
Narration: You only change two things. lib decides which assignments exist. tfvars decides what the parameters are.
Visual: the gear outputs a management group tree. Nodes light up level by level, then assignments stick onto each node like stickers.
Narration: The provider does the calculating. The modules use AzAPI to build. First management groups, then definitions, then assignments, and finally grant access to the managed identities.
Visual: in the code, depends_on is crossed out and replaced with policy_assignments_dependencies.
Narration: Express order with dependency variables. Don't use depends_on.
Module 3 · Bicep: AVM modules and deployment stacks
- Read the Bicep starter code: each management group has one
main.bicepandmain.bicepparam, which internally callbr/public:avm/ptn/alz/empty. The library JSON is committed with the repository and loaded withloadJsonContent.platform-landing-zone.yamlis rendered into each module's parameters. - Explain the three deployment stack settings: scope (RG / subscription / management group),
actionOnUnmanage(detachAll / deleteResources / deleteAll),denySettingsMode(none / denyDelete / denyWriteAndDelete), and excluded principals (up to 5). - Know that the Accelerator's Bicep pipeline deploys with deployment stacks (DenySettingsMode None, ActionOnUnmanage DeleteAll), so "deleting a line from the template" deletes real resources.
- Know the retirement date of classic ALZ-Bicep and the "hard blockers" for migrating (covered in detail in Module 7).
targetScope, modules, .bicepparam), Hour 1, Module 6. Importance: ★★★★☆ (required for Bicep teams; Terraform teams also benefit from understanding deployment stacks)What: what the Bicep (AVM) starter code looks like
Path (under templates/) | Contents |
|---|---|
core/governance/mgmt-groups/int-root/main.bicep | Intermediate root: loads 5 custom roles, all ALZ custom definitions and policy sets, and the assignments on root. Calls br/public:avm/ptn/alz/empty:0.3.6 |
core/governance/mgmt-groups/platform/…, landingzones/landingzones-corp … | One directory per management group, each with its own assignments. Some include main-rbac.bicep (grants access to DINE managed identities across scopes). |
core/governance/lib/alz/*.json | ALZ library JSON assets, organized into directories by management group, committed in the repository |
core/governance/tooling/alz_library_metadata.json | Declares the dependency on platform/alz 2026.11.0 |
core/governance/tooling/Update-AlzLibraryReferences.ps1 | Scans lib/alz and updates the loadJsonContent lists for the four variables (role definitions, policy definitions, policy sets, assignments) in each main.bicep. Supports -WhatIf |
core/logging/, networking/hubnetworking/, networking/virtualwan/ | Management resources such as Log Analytics; hub-spoke or vWAN |
Configuration has two layers. You edit config/inputs.yaml and config/platform-landing-zone.yaml (MG IDs, subscription placement, feature flags). Bootstrap renders them into each module's main.bicepparam. At deploy time, the pipeline deploys each module one at a time, in the order given by deployment_files in .config/ALZ-Powershell.config.json. Policy parameter overrides are passed through parPolicyAssignmentParameterOverrides (for example logAnalytics, emailSecurityContact).
What: deployment stacks
Microsoft.Resources/deploymentStacks is a resource that records "which resources this template manages." It can be created at resource group, subscription or management group scope (a management group scope stack deploys resources into a subscription, specified with --deployment-subscription). It does two things that a regular deployment does not:
| Capability | Parameter (CLI) | Values and meaning |
|---|---|---|
| What happens to resources that are no longer managed | --action-on-unmanage | detachAll: only detaches from management; resources are kept (the safest default). deleteResources: deletes the resources; the resource group is only detached. deleteAll: deletes both the resources and the resource group. |
| Protect managed resources | --deny-settings-mode | none; denyDelete: blocks deletion; denyWriteAndDelete: blocks modification and deletion (implemented as a deny assignment, applies only to the control plane) |
| Exceptions to deny settings | --deny-settings-excluded-principals, --deny-settings-excluded-actions, --deny-settings-apply-to-child-scopes | Up to 5 principals (exceeding this does not produce an error, so use groups); up to 200 actions; the child scope switch decides whether child resources not declared in the template are also protected |
- Tool requirements: Azure CLI ≥ 2.61.0 or Az PowerShell ≥ 12.0.0. The portal can only view and delete stacks, not create them.
- Built-in roles: Azure Deployment Stack Contributor (manages stacks, cannot create or delete deny assignments) and Azure Deployment Stack Owner (includes deny settings). Enforcement of
deploymentStacks/manageDenySetting/actionis rolling out region by region. - Deny settings only protect explicitly declared resources. Implicit resources, such as VMs that AKS creates automatically, and data-plane objects, such as Key Vault secrets and Blob containers, are not protected.
- The official guidance is to place the stack at a higher scope. To protect resources in a subscription, put the stack in the parent management group. This way, fewer people can change the stack (and its deny assignment).
Why: why the ALZ Bicep implementation uses stacks
- Deletion is declaration: Bicep has no state. Without a stack, deleting a policy assignment from the template leaves the assignment in Azure (incremental deployment). The Accelerator's deployment scripts use
New-AzManagementGroupDeploymentStack/New-AzSubscriptionDeploymentStackwithDenySettingsMode = "None"andActionOnUnmanage = "DeleteAll", which makes the repository the single source of truth. - Why deny settings are not enabled: platform resources receive many legitimate writes from outside the pipeline, such as DINE remediation and Defender auto-provisioning. A blanket deny assignment would break them. When needed, you can turn on
denyDeletefor specific stacks and exclude the group that holds the remediation identities.
When: Bicep or Terraform
| Lean toward Bicep (AVM) | Lean toward Terraform (AVM) |
|---|---|
| Team uses only Azure and already has ARM/Bicep experience; does not want to maintain state | Multi-cloud or an existing Terraform platform; needs plan file approval and a mature module ecosystem |
| Wants to protect critical resources with deployment stack deny settings | Needs moved / import for refactoring and migration |
| Can accept the limits of what-if (it cannot catch every failure, such as parameter removal) | Can keep state secure (private storage, Entra authentication) |
- "denyDelete on a deployment stack blocks everyone" — principals on the exclusion list are not restricted. Also, deny settings only cover the control plane and explicitly declared resources.
- "detachAll deletes resources" — No. It only stops the stack from tracking them. The resources are left as they are.
- "deleteAll always deletes the resource group" — If the resource group contains resources outside the stack, neither the resource group nor those resources will be deleted.
- "Classic ALZ-Bicep can still be selected in the Accelerator" — It was removed from the Accelerator on 2026-02-16, and the repository will be archived on 2027-02-16.
The three states and two settings of a deployment stack
Deployment order in the Bicep starter code
Deployment stack simulator: change the template, delete resources, test deny settings
First choose the two settings, then click "Deploy v1". Then try each operation in turn and watch the resource's status / denyStatus and the ARM response in the terminal (error codes are examples; use the actual codes).
Core commands
| Command | Purpose |
|---|---|
az stack group|sub|mg create | Create or update a stack (the CLI has no set command; running create again updates it) |
az stack sub show -n NAME -o json | View the status and denyStatus of each resource in resources[] |
az stack mg delete --management-group-id MG -n NAME --action-on-unmanage detachAll | Delete the stack and decide what happens to its resources |
az stack sub export -n NAME | Export the template the stack uses |
--bypass-stack-out-of-sync-error | Use only after confirming the resource list is correct. Bypasses the "out of sync" protection. |
Management group scope stack (same type as the Accelerator's int-root deployment)
az stack mg create \ --name alz-int-root \ --management-group-id alz \ --location canadacentral \ --template-file templates/core/governance/mgmt-groups/int-root/main.bicep \ --parameters templates/core/governance/mgmt-groups/int-root/main.bicepparam \ --action-on-unmanage deleteAll \ --deny-settings-mode none
Module call in the Bicep starter code (excerpt from int-root/main.bicep)
targetScope = 'managementGroup'
param intRootConfig alzCoreType
param parLocations array = [ deployment().location ]
param parPolicyAssignmentParameterOverrides object = {}
var alzPolicyDefsJson = [
loadJsonContent('../../lib/alz/Append-AppService-httpsonly.alz_policy_definition.json')
// … a long list maintained by Update-AlzLibraryReferences.ps1
]
module intRoot 'br/public:avm/ptn/alz/empty:0.3.6' = {
// Creates/updates management groups, and deploys definitions, policy sets, role definitions and assignments
}
Refresh library references (after upgrading the library)
./templates/core/governance/tooling/Update-AlzLibraryReferences.ps1 -WhatIf # see which variables it will change first ./templates/core/governance/tooling/Update-AlzLibraryReferences.ps1 git diff --stat templates/core/governance/mgmt-groups
Scanning lib/alz ... int-root/main.bicep alzPolicySetDefsJson: +1 -0 landingzones/main.bicep alzPolicyAssignmentsJson: ~1 2 files changed, 3 insertions(+), 1 deletion(-)
Output is illustrative. The official "Updating Your Deployment" guide explains that during Bootstrap the entire templates directory is pushed to your repository, and you maintain AVM module versions yourself (for example, changing br/public:avm/res/network/virtual-network:0.2.0 to a newer version). They are not pulled on demand.
Lab 3: resource group scope deployment stack + denyDelete (about 12 minutes, no cost)
// stack-lab.bicep
param location string = resourceGroup().location
param includeRouteTable bool = true
resource nsg 'Microsoft.Network/networkSecurityGroups@2024-05-01' = {
name: 'nsg-stack-lab-cc'
location: location
tags: { env: 'lab', owner: 'platform-team', costCenter: 'cc-1000', workload: 'stack-lab' }
}
resource rt 'Microsoft.Network/routeTables@2024-05-01' = if (includeRouteTable) {
name: 'rt-stack-lab-cc'
location: location
properties: { disableBgpRoutePropagation: true }
}az group create -n rg-stack-lab-cc -l canadacentral --tags env=lab owner=platform-team costCenter=cc-1000 workload=stack-lab
az stack group create -n st-lab -g rg-stack-lab-cc --template-file stack-lab.bicep \
--action-on-unmanage detachAll --deny-settings-mode denyDelete
az stack group show -n st-lab -g rg-stack-lab-cc --query "resources[].{id:id,status:status,deny:denyStatus}" -o table
Id Status Deny ----------------------------------------------------- -------- ---------- .../networkSecurityGroups/nsg-stack-lab-cc managed denyDelete .../routeTables/rt-stack-lab-cc managed denyDelete
az network nsg delete -g rg-stack-lab-cc -n nsg-stack-lab-cc. It is denied even if you are an Owner, because deny assignments take precedence over role assignments. Record the error code.--parameters includeRouteTable=false. Use --action-on-unmanage detachAll and then deleteResources to see whether the route table is "detached" or "deleted". (Before the second run, set the parameter back to true to bring the route table back under management.)az stack group delete -n st-lab -g rg-stack-lab-cc --action-on-unmanage deleteAll --yes, then az group delete -n rg-stack-lab-cc --yes.az stack mg create … --deployment-subscription <sub> (the template must change to targetScope = 'subscription' and deploy to a resource group through a module). Compare the two placements for "who can change deny settings".Case 1: a cleanup PR deleted the Log Analytics workspace
Problem: someone "cleaned up" the parameter files in the Bicep repository and mistakenly changed the workspace resource condition in the logging module to false. The CD pipeline deployed the stack with ActionOnUnmanage DeleteAll, and the workspace was deleted. Lesson: when using DeleteAll, PR reviews must check Delete in the what-if output. For resources that hold data, such as workspaces, put them in a separate stack with detachAll, or require extra approval in CI when the Delete count > 0. A deleted workspace can be recovered within the retention period (see the Log Analytics documentation for details).
Case 2: denyWriteAndDelete broke Defender auto-provisioning
Problem: to "protect the platform," the team turned on denyWriteAndDelete for the connectivity stack. After that, many DINE remediation tasks and Defender auto-provisioning failed. Cause: deny assignments apply to every principal that is not excluded, including policy managed identities. Fix: switch to denyDelete, and put the managed identities used for remediation into an Entra group, which is added as an excluded principal (total ≤ 5).
Case 3: migration window for classic ALZ-Bicep customers
Problem: the customer is still using classic ALZ-Bicep and is worried that policy updates will stop after the 2027-02-16 archive. Fix: follow the official migration guide to converge in place. Align the management group IDs and log resource names in the AVM configuration with the classic deployment (classic uses nested IDs such as alz-landingzones-corp, while AVM defaults to flat IDs). Then rebuild the policy objects in stages (Module 7).
Common errors and fixes
DenyAssignmentAuthorizationFailed … is not authorized to perform action 'Microsoft.Network/networkSecurityGroups/delete' … because of a deny assignment (use the actual text)
Cause: the resource is protected by a deployment stack deny setting. Diagnose: az role assignment list does not show it. Use az stack group show … --query denySettings, or in the portal go to Access control (IAM) → Deny assignments. Fix: make the change by updating the stack (change the template or denySettings). In an emergency, add the person making the change to the excluded group.
The deployment stack '…' might not have an accurate list of managed resources …
Cause: the stack's resource list is out of sync with reality (for example, the last deployment partly failed). Fix: first redeploy with the same template and parameters. Only use --bypass-stack-out-of-sync-error after confirming resources[] is correct.
Six principals excluded, but the sixth is still denied
Cause: up to 5 principals can be excluded, and exceeding that produces no error. Fix: put the identities into an Entra group and exclude the group. Test nested groups first.
InvalidPolicyParameterUpdate: policy parameters cannot be removed during policy update
Cause: in a new library version, a custom policy definition removed or renamed a parameter. Azure does not allow a parameter to be removed in place, and what-if shows it as a normal Modify, so it is not caught. Fix: follow the staged approach in the migration guide: delete assignments first, then policy sets, then definitions, and then redeploy (Module 7).
The what-if identity gets AuthorizationFailed … deployments/whatIf/action when running what-if
Cause: the what-if identity has only Reader and is missing the custom role created by Bootstrap (which includes Microsoft.Resources/deployments/whatIf/action and validate/action). Fix: check whether that custom role assignment exists on the intermediate root.
1. List all "detached" resources in the subscription-scope stack st-platform.
az stack sub show -n st-platform --query "resources[?status=='detached'].id" -o tsv
2. Deploy a management group scope stack with denyDelete, excluding the platform admins group and the remediation identity group.
az stack mg create -n st-conn --management-group-id connectivity -l canadacentral \ --template-file main.bicep --deployment-subscription <conn-sub-id> \ --action-on-unmanage detachAll --deny-settings-mode denyDelete \ --deny-settings-excluded-principals "<platform-admins-group-id> <remediation-group-id>"
You are responsible for the Bicep platform repository. How do you make sure that "the repository is the single source of truth" and "an accidental delete PR does not remove resources that hold data" are both true?
① Use deleteAll for governance stacks (management groups, policy, roles), because these objects hold no data and must match the repository. ② Put resources that hold data, such as logs, keys and storage, in a separate detachAll stack, turn on denyDelete for them, and exclude the platform admins group. ③ Have CI parse the what-if output, and require a second approver when Delete appears. ④ As a last line of defense, turn on soft delete and recovery on Log Analytics and Key Vault.
Verified videos
Official documentation
- Create and deploy Azure deployment stacks in Bicep
- alz-bicep-accelerator
- Migration from Classic (ALZ-Bicep → AVM)
- ALZ-Bicep (classic deprecation notice)
Video storyboard (about 90 seconds)
This lesson material cannot generate video or MP3 directly. The storyboard and narration script are provided, so you can hand them to a video tool.
Visual: a box labeled deploymentStack holds three resource cards. A "denyDelete" seal is stuck on the outside of the box.
Narration: The stack remembers what it manages, and it can put a deny seal on those resources.
Visual: the route table is crossed out in the template, with three branches: detach (the card leaves the box), deleteResources (the card disappears), deleteAll (the card and the resource group disappear together).
Narration: When the template shrinks, actionOnUnmanage decides what happens to the resources.
Visual: an operator's delete request is blocked by a red shield, while a pipeline identity with an "excluded group" badge gets through.
Narration: Deny assignments take precedence over role assignments. Up to five principals can be excepted, and it's best to use a group.
Module 4 · Platform pipelines: GitHub Actions and Azure Pipelines
- Break down the two pipelines the Accelerator generates: 01 Continuous Integration (PRs: fmt, validate, plan, and comment on the PR) and 02 Continuous Delivery (main / manual: plan → approval → apply, with optional destroy).
- Explain the three lines of defense: branch protection (changes must go through a PR), environment approval (the apply environment only allows protected branches and requires an approving team), and OIDC subject binding to
environmentandjob_workflow_ref. - Make sure "the approved plan is the executed plan": the plan file is the artifact, runs in the same concurrency group are serialized, and a stale plan fails and must be rerun.
- Add scheduled drift detection (
terraform plan -detailed-exitcode) and decide who handles drift when it is found.
What: the pipelines the Accelerator generates (GitHub variant)
| Workflow | Trigger | Jobs and environment | Identity |
|---|---|---|---|
01 Azure Landing Zones Continuous Integration (main repository, calls ci-template.yaml in the template repository) | pull_request to main; manual | validate (fmt -check, init, validate) → plan; environment alz-mgmt-plan; permissions id-token: write, contents: read, pull-requests: write | plan UAMI (Reader on the intermediate root) |
02 Azure Landing Zones Continuous Delivery (calls cd-template.yaml) | push to main; manual (terraform_action: apply / destroy) | plan job (plan environment): plan -out=tfplan, uploads the entire module directory together with the plan file as an artifact → apply job (apply environment, requires approval): downloads the artifact and runs apply tfplan | plan UAMI → apply UAMI (Owner on the intermediate root) |
Some details are worth noting. The Terraform CLI version is an input (the default is set in the calling workflow). All Actions are pinned to a commit SHA. The apply job sets AZAPI_RETRY_GET_AFTER_PUT_MAX_TIME=60m. Both jobs have a concurrency group to keep two runs from competing for the same state. The Azure DevOps variant has the same structure: two pipelines (names start with 01 / 02), two environments (the apply environment requires approval), and two workload identity federated service connections. The templates live in a separate repository.
Why: why there are so many layers
| Threat | Defense |
|---|---|
| Someone pushes directly to main, bypassing review | Branch protection: changes must go through a PR, history is linear, and stale approvals are dismissed (Bootstrap requires 1 approval when there is more than 1 approver) |
| Someone changes the workflow on a PR branch to steal the apply identity | The apply environment's deployment branch policy only allows protected branches. The OIDC subject includes environment, so a PR can't get a token for the apply environment. |
| Someone creates a new workflow in the main repository that references the apply environment | The subject also includes job_workflow_ref, so it only matches reusable workflows in the template repository (two-repository setup). |
| The plan reviewed for approval is not the one that is finally executed | The plan file is the artifact. apply only runs that file. If the state has changed, the plan is stale, and Terraform refuses to run it. |
| Two runs change the state at the same time | concurrency + blob lease lock in the azurerm backend |
| Long-lived credentials leak | No secrets: UAMI + federated credentials. Workload identities are not affected by Azure's enforced MFA (hour 3). |
How: what the OIDC subject looks like
The default GitHub subject looks like repo:contoso/alz-mgmt:environment:alz-mgmt-apply. The Accelerator uses github_actions_repository_oidc_subject_claim_customization_template to customize the repository's subject to include repository, environment and job_workflow_ref, using the organization's and repository's immutable IDs. The resulting federated credential subject looks like:
repo:contoso@<org-id>/alz-mgmt@<repo-id>:environment:alz-mgmt-apply:job_workflow_ref:contoso/alz-mgmt-templates/.github/workflows/cd-template.yaml@refs/heads/main
Consequences: ① Renaming or transferring a repository does not let someone else "claim" the same name and get a token. ② When you add a new workflow yourself (such as drift detection), you must add a federated credential for it, or reuse a reusable workflow that already exists in the template repository. Otherwise you get AADSTS70021. For the 20-credential limit and propagation delay of federated credentials, see hour 3.
When: drift detection and who fixes it
- Run
terraform plan -detailed-exitcodeevery day on a schedule with the plan identity: exit code 0 = no changes, 1 = error, 2 = differences found. When differences are found, create an Issue or work item, rather than applying automatically. - Drift comes from three sources: someone changed platform resources in the portal (roll back or codify the change); Azure-side behavior changes (such as a new version of a built-in policy or a service default); library or module versions are not pinned (they should be pinned).
- The "normal writes" from DINE remediation and Defender auto-provisioning usually land on attributes that the module handles with
ignore_changesor does not track. If the same drift keeps coming back, fix the code instead of adding an exception.
- "The plan identity is read-only, so a plan from a PR is harmless" — The plan identity can read all platform configuration and state files, including sensitive values in outputs. When a PR comes from an external fork, don't run a plan with the identity.
- "Approving apply is enough" — If the apply job reruns the plan instead of executing the artifact, the approver is not seeing what actually runs.
- "If drift detection finds a difference, automatically apply to revert it" — This may overwrite an emergency fix. Notify first, then decide.
- "Azure DevOps doesn't support this kind of split" — It does: two service connections (each with its own federated workload identity), environment approvals and checks, and a template repository with required template checks.
Sequence diagram: one platform change from PR to apply
Pipeline gates and token exchange (with failure injection)
Choose a trigger and a scenario, then step through each gate: branch protection, environment deployment policy, approval, OIDC subject matching, state lock, and whether the plan has expired.
Key snippets
| Snippet / command | Purpose |
|---|---|
permissions: { id-token: write, contents: read } | Allows the job to request an OIDC token (see GitHub hour 3) |
environment: alz-mgmt-apply | The token's subject includes the environment, which triggers approval and branch policy |
ARM_USE_OIDC: true, ARM_USE_AZUREAD: true | azurerm / azapi sign in with OIDC; the backend uses Entra authentication to access Blob storage |
terraform plan -out=tfplan → upload artifact → terraform apply tfplan | What is approved is what runs |
terraform plan -detailed-exitcode | Drift detection: 0 no changes / 1 error / 2 differences found |
gh api repos/{owner}/{repo}/actions/oidc/customization/sub | View the repository's OIDC subject customization |
Drift detection: place in a reusable workflow in the template repository (GitHub)
# alz-mgmt-templates/.github/workflows/drift-template.yaml
name: Drift Detection (template)
on:
workflow_call:
inputs:
root_module_folder_relative_path: { type: string, default: '.' }
jobs:
drift:
runs-on: ubuntu-latest
environment: alz-mgmt-plan # plan identity only
permissions: { id-token: write, contents: read, issues: write }
env:
ARM_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
ARM_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
ARM_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
ARM_USE_OIDC: true
ARM_USE_AZUREAD: true
steps:
- uses: actions/checkout@v4 # in production, pin to a commit SHA as the Accelerator does
- uses: hashicorp/setup-terraform@v3
with: { terraform_wrapper: false }
- name: Init
run: |
terraform -chdir="${{ inputs.root_module_folder_relative_path }}" init \
-backend-config="resource_group_name=${{ vars.BACKEND_AZURE_RESOURCE_GROUP_NAME }}" \
-backend-config="storage_account_name=${{ vars.BACKEND_AZURE_STORAGE_ACCOUNT_NAME }}" \
-backend-config="container_name=${{ vars.BACKEND_AZURE_STORAGE_ACCOUNT_CONTAINER_NAME }}" \
-backend-config="key=terraform.tfstate"
- name: Plan (detailed exit code)
id: plan
run: |
set +e
terraform -chdir="${{ inputs.root_module_folder_relative_path }}" plan -lock=false -input=false -detailed-exitcode -no-color > plan.txt
echo "code=$?" >> "$GITHUB_OUTPUT"
- name: Open issue on drift
if: steps.plan.outputs.code == '2'
run: gh issue create --title "Platform drift detected $(date -u +%F)" --body-file plan.txt
env: { GH_TOKEN: ${{ github.token }} }
- name: Fail on error
if: steps.plan.outputs.code == '1'
run: exit 1
# alz-mgmt/.github/workflows/03-drift.yaml (caller)
name: 03 Drift Detection
on:
schedule: [ { cron: '0 6 * * *' } ] # every day at 06:00 UTC
workflow_dispatch: {}
jobs:
drift:
uses: contoso/alz-mgmt-templates/.github/workflows/drift-template.yaml@main
permissions: { id-token: write, contents: read, issues: write }
# Add a federated credential to the plan UAMI that matches this reusable workflow (copy the subject format from the existing credentials and only replace the file name) az identity federated-credential list -g rg-alz-mgmt-identity-canadacentral-1 \ --identity-name id-alz-mgmt-canadacentral-plan-1 --query "[].subject" -o tsv az identity federated-credential create -g rg-alz-mgmt-identity-canadacentral-1 \ --identity-name id-alz-mgmt-canadacentral-plan-1 -n drift-plan \ --issuer https://token.actions.githubusercontent.com \ --subject "repo:contoso@<org-id>/alz-mgmt@<repo-id>:environment:alz-mgmt-plan:job_workflow_ref:contoso/alz-mgmt-templates/.github/workflows/drift-template.yaml@refs/heads/main" \ --audiences api://AzureADTokenExchange
-lock=false keeps the read-only drift detection from competing for the lock with an apply in progress. The cost is that it may read an intermediate state. For strict consistency, remove it and accept occasional lock waits. The Azure DevOps equivalent: a schedules: trigger, plus AzureCLI@2 or TerraformTask using the plan service connection. When the exit code is 2, create a work item with the REST API (see ADO hour 3 · IaC pipelines).
Lab 4: review the generated pipelines and add drift detection (about 12 minutes)
ci-template.yaml and cd-template.yaml in the Accelerator output or in the official repository accelerator-bootstrap-modules/alz/github/actions/terraform/. Find the plan artifact upload, apply tfplan, concurrency, the two environment entries, and the Actions pinned to SHAs.gh api repos/contoso/alz-mgmt/actions/oidc/customization/sub, and confirm that include_claim_keys is ["repository","environment","job_workflow_ref"].Enable-DDoS-VNET assignment on connectivity to "Disabled". Run 03 Drift Detection manually. You should expect exit code 2 and an automatically opened Issue.policy_assignments_to_modify), then run again. The exit code should be 0.terraform plan -detailed-exitcode; echo $? locally to see the three exit codes.Case 1: the apply environment is configured to "allow all branches"
Problem: While debugging, someone temporarily changed the deployment branch policy on the apply environment to allow all branches, then forgot to change it back. A manual run from a feature branch applied unreviewed code. Fix: Bring the environment configuration under IaC too. Bootstrap is already Terraform, so changes should go through it or through a separate GitHub configuration repository. Use organization audit log alerts to flag changes to environment protection.
Case 2: Approval took two days, and apply failed because the plan had expired
Problem: Friday's plan was approved on Monday. In the meantime, another PR had already been applied. When the old plan ran, Terraform reported “Saved plan is stale”. Fix: This is the protection working as intended. Rerun CD (new plan, new approval). Also set a reasonable wait timeout on the apply environment so approvals cannot hang indefinitely.
Case 3: Drift detection reports a Defender settings change every day
Problem: Every day the plan shows a sub-setting of the Defender plan being reverted. Cause: The Deploy-MDFC-Config assignment (DINE) in the library and the Defender settings explicitly managed in Terraform are fighting over the same property. Fix: Pick one owner: either policy or code. The ALZ IaC Accelerator starter code takes the policy approach (set the assignment's parameters in tfvars).
Common errors and fixes
AADSTS70021: No matching federated identity record found for presented assertion.
Cause: The token subject does not exactly match the federated credential: the environment name, the branch, job_workflow_ref, or the repository uses a custom subject. Diagnosis: Print github.workflow_ref and the environment in the workflow (do not print the token itself), then compare with az identity federated-credential list. Fix: Add a federated credential for the new workflow. Note that changes can take time to propagate.
Error acquiring the state lock … state blob is already locked
Cause: Another run is already in plan or apply, or a previous run exited abnormally and left its lock behind. Fix: Wait. After confirming that no run is active, run terraform force-unlock <LOCK_ID> (only if you are sure). Use concurrency to prevent parallel runs.
Error: Saved plan is stale
Cause: The state was changed after the plan was generated. Fix: Rerun the plan and the approval. Do not bypass this check.
AuthorizationPermissionMismatch / 403 when reading the state blob
Cause: The identity is missing Storage Blob Data Contributor on the state container, or the backend does not set use_azuread_auth while the storage account has shared key access disabled. Fix: Grant the data-plane role, and set ARM_USE_AZUREAD=true in the backend settings.
The 01 CI check on a PR fails in a fork: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable
Cause: By default, a pull_request run from a fork cannot get an OIDC token. Fix: This is expected behavior. For the platform repository, do not accept external forks, or run only the checks that do not need identity on forks (fmt, validate, tflint).
1. Reproduce the “plan as artifact” pattern of CD locally: generate the plan, review it, then apply that exact plan.
terraform plan -out=tfplan -input=false terraform show tfplan | less terraform apply -input=false tfplan
2. List every federated credential subject on the apply UAMI, and confirm that none is a broad credential pointing at a branch.
az identity federated-credential list -g rg-alz-mgmt-identity-canadacentral-1 \
--identity-name id-alz-mgmt-canadacentral-apply-1 --query "[].{name:name,subject:subject}" -o tableAn audit requires that “any platform change has two people involved, and you can prove that what ran is exactly what was approved”. How does the GitHub pipeline generated by the Accelerator meet this?
① Branch protection: changes must go through a PR, require at least 1 approval from someone other than the author, and dismiss stale approvals. ② Apply environment: approval by a review team, only protected branches allowed, and self-approval prevented (the “Prevent self-review” setting on GitHub environments). ③ In CD, the plan file is the artifact; apply runs that file, and the artifact and run records are retained. ④ The OIDC subject is bound to the environment and the template repository workflow, so Entra sign-in logs can be traced back to the run. ⑤ Changes to the template repository also go through a PR. Evidence: PR records, environment approval records, plan summaries in the run logs, and Entra workload identity sign-in logs.
Verified training videos
Official documentation and related courses
- Phase 3 – Run
- GitHub: About security hardening with OpenID Connect
- GitHub hour 3 · IaC pipeline
- Terraform hour 5 · GitHub Actions + OIDC · Drift detection
Video storyboard script (about 90 seconds)
This courseware cannot generate video or MP3 directly. A storyboard and narration script are provided for a video tool to use.
On screen: A PR opens, the CI badge turns green, and a plan summary appears in the comments.
Narration: On the PR, the plan runs with a read-only identity only, and the result is written back to the PR.
On screen: After the merge, CD generates a tfplan file and packs it into an “artifact” box. An approval light turns on before the apply job.
Narration: What gets approved is the exact plan inside that box.
On screen: A forged workflow holds up a JWT and knocks on Entra's door. The job_workflow_ref in the subject does not match, and the request is rejected.
Narration: The subject is bound to the environment and the template workflow. Without a token, the workflow cannot touch the platform.
Module 5 · Subscription Vending
- Describe the CAF vending flow: collect data → the request pipeline generates a parameter file and opens a PR → validation and approval → merge triggers the deployment pipeline → delivery and handover.
- Understand the asynchronous behavior of the subscription alias API (
Microsoft.Subscription/aliases), the billing scope format,workload(Production / DevTest), and the billing permissions required. - Using
Azure/avm-ptn-alz-sub-vending/azure0.3.4, write a vending request covering: the subscription (new or existing), management group placement, resource groups, NSG, spoke VNet and hub peering, UAMI + federated credentials, role assignments, and budget. - Design for failure: which errors should be caught at the PR stage, which happen midway through apply, and how to “fix forward” instead of rolling back blindly.
What: Vending = data + pipeline + module
The CAF implementation guidance (Azure Architecture Center, updated 2025-12) splits vending into three jobs: collect the request data (an ITSM ticket or a Power Apps portal, with approvals and business logic), start the platform automation (the request pipeline generates one JSON / YAML / TFVARS parameter file per subscription, creates a branch, commits, and opens a PR; the PR triggers validation, such as checking whether the IP range is still available), and create the subscription with IaC (after the merge, the deployment pipeline calls the vending module). After that, the platform team hands the subscription over to the application team, which adjusts the budget and deploys workloads. Governance of the subscription (management groups, policy) stays with the platform team.
| Deployment pipeline tasks (CAF) | Matching inputs in the module (Terraform 0.3.4) |
|---|---|
| Identity: subscription ownership, workload deployment identity | role_assignments, user_managed_identities (including federated_credentials_github / Terraform Cloud / advanced FIC) |
| Governance: management group placement, subscription Owner, subscription-level RBAC, subscription-level policy, Defender registration | subscription_management_group_association_enabled + subscription_management_group_id; subscription_register_resource_providers_and_features (the default list comes from the resource providers azurerm requires) |
| Networking: spoke VNet, peered with the regional hub | virtual_network_enabled + virtual_networks (hub_peering_enabled, hub_network_resource_id, mesh_peering_enabled, vWAN connection, and either ipam_pools or address_space) |
| Budget | budget_enabled + budgets (amount, time_grain, notification thresholds for Actual / Forecasted) |
| Reporting: update IPAM, write back to the ticket, notify the application team | Module outputs such as subscription_id, resource_id, and virtual_network_resource_ids, used by later pipeline steps |
How: the mechanics of the subscription alias API
PUT /providers/Microsoft.Subscription/aliases/{aliasName}?api-version=2021-10-01. The request body includesbillingScope,displayName,workload(onlyProductionorDevTest), and optionaladditionalProperties(managementGroupId,subscriptionOwnerId,subscriptionTenantId,tags).- The response first returns
provisioningState: Accepted. Poll the same URL until it returnsSucceededwith asubscriptionId. Aliases are idempotent: a second PUT with the same name returns the same subscription. This is why the vending pipeline can be safely rerun. - Without
additionalProperties, the caller (such as the pipeline's service principal) automatically becomes the Owner of the new subscription. New subscriptions land in the tenant's default management group (the hierarchy settings from hour 1), so the module then associates the subscription with the target management group. - Right after a new subscription is created, ARM needs time to become consistent everywhere. The Terraform module provides
wait_for_subscription_before_subscription_operations(create waits 30 seconds by default).
| Billing agreement | billingScope format | Who can create |
|---|---|---|
| EA | /providers/Microsoft.Billing/billingAccounts/{ba}/enrollmentAccounts/{ea} | Enterprise Administrator or enrollment account Owner. A service principal needs the enrollment account Owner to grant SubscriptionCreator through enrollmentAccountRoleAssignments (2019-10-01-preview API). Each enrollment account can hold up to 5,000 subscriptions (canceled, deleted, and transferred subscriptions count too). |
| MCA | /providers/Microsoft.Billing/billingAccounts/{ba}/billingProfiles/{bp}/invoiceSections/{is} | Owner / Contributor / Azure subscription creator on the invoice section |
| MPA (CSP) | /providers/Microsoft.Billing/billingAccounts/{ba}/customers/{customerId} | The corresponding role on the partner side |
| Pay-as-you-go / free trial | — | Cannot be created programmatically: create the subscription manually. The remaining steps (placement, networking, identity, budget) can still be automated (the module uses its “existing subscription” mode). |
The ALZ PowerShell module provides Grant-SubscriptionCreatorRole to grant the billing role to the vending identity. Besides billing permissions, the vending identity also needs permission to move subscriptions under the target management group, and Network Contributor on the resource group that holds the hub VNet (to create the hub-side peering).
Why: why CAF insists on “one file and one state per subscription”
- Blast radius: If one state manages 200 subscriptions, a single bad for_each key can replace dozens of peerings in one plan. With one state per subscription, the worst case affects just one.
- Performance: A plan only refreshes the resources of that one subscription.
- Audit: Git history naturally records who asked for what, and when.
When: Terraform module or Bicep module
Terraform Azure/avm-ptn-alz-sub-vending/azure 0.3.4 | Bicep br/public:avm/ptn/lz/sub-vending 0.8.0 |
|---|---|
Built on AzAPI (~> 2.12) and Terraform ~> 1.10. It replaces the older Azure/lz-vending/azurerm (last version 7.0.3, 2025-11). | It is the successor to the bicep-lz-vending repository (after moving into AVM, the version restarted at 0.1.0). Some features, such as resource provider registration, rely on deployment scripts and need deploymentScript* related parameters. |
Inputs are organized as *_enabled flags plus maps. Supports IPAM pool allocation, mesh peering, and multiple VNets. | Parameters such as subscriptionAliasEnabled, subscriptionBillingScope, subscriptionManagementGroupId, virtualNetworkAddressSpace, hubNetworkResourceId, budgetAmount, and pimRoleAssignments |
- “Vending just means creating a subscription.” Creating the subscription is only the first step. A subscription without placement, networking, identity, and budget is a blank check.
- “If it fails, roll back with terraform destroy.” Destroying the vending module means canceling the subscription (the module first tries to delete NetworkWatcherRG with the az CLI), and the application team may already be using it. Most failures should be fixed by correcting the parameters and rerunning (fix forward).
- “IP conflicts only show up as an Azure error during apply.” The
VnetAddressSpacesOverlaperror appears only when peering, and by then the subscription is already created. Catch it in PR validation by checking against IPAM, or useipam_poolsdirectly. - “You cannot do vending without an EA.” You can use the existing-subscription mode (
subscription_alias_enabled = false+subscription_id).
Architecture diagram: requests, platform automation, and delivery
Core animation: one vending request, from PR to a usable new subscription (including approval and failure rollback)
Choose a billing method and a failure, then click “Play” or “Next”. The top row shows the pipeline gates; the bottom row shows the steps the module actually runs during apply (order simplified from the module's resource dependencies). The APIs and errors in the logs are examples; check the actual output.
Core commands
| Command | Purpose |
|---|---|
az billing account list | Find the billing account and enrollment account (EA) or the invoice section (MCA), and get the billing scope |
az account alias create --name … --billing-scope … --display-name … --workload Production | Create the subscription directly with the alias API (requires the account and alias extensions) |
az account alias show --name … | Check provisioningState and subscriptionId |
az account management-group subscription add --name corp --subscription <id> | Place it in the management group manually (the module does this for you) |
terraform init -backend-config="key=vending/<name>.tfstate" | One subscription, one state |
Request file (the application team only edits this)
# requests/myapp-dev.yaml name: myapp-dev subscription: existing_id: "<app-sub-id>" # With EA, change to alias + billing_scope display_name: sub-lz-corp-myapp-dev workload: DevTest management_group: corp owner_group_object_id: "<myapp-team-group-id>" cost_center: cc-2001 network: address_space: 10.2.0.0/16 app_subnet: 10.2.1.0/24 github: organization: contoso repository: myapp environment: dev budget_monthly: 200 budget_contacts: [ "myapp-team@example.com" ]
Vending root module (maintained by the platform team)
# vending/main.tf
terraform {
required_version = "~> 1.10"
required_providers { azapi = { source = "Azure/azapi", version = "~> 2.12" } }
backend "azurerm" {
resource_group_name = "rg-alz-iac-cc"
container_name = "tfstate-vending"
use_azuread_auth = true # storage_account_name and key are passed in at init
}
}
provider "azapi" {}
variable "request_file" { type = string }
variable "hub_vnet_id" { type = string } # vnet-hub-cc from hour 4
locals { r = yamldecode(file(var.request_file)) }
module "lz" {
source = "Azure/avm-ptn-alz-sub-vending/azure"
version = "0.3.4"
location = "canadacentral"
subscription_alias_enabled = false # No EA: use an existing subscription
subscription_id = local.r.subscription.existing_id
subscription_update_existing = true # Update display name and tags
subscription_display_name = local.r.subscription.display_name
subscription_tags = { env = "dev", owner = local.r.name, costCenter = local.r.cost_center, workload = "myapp" }
subscription_management_group_association_enabled = true
subscription_management_group_id = local.r.management_group
resource_group_creation_enabled = true
resource_groups = {
net = { name = "rg-lz-${local.r.name}-net-cc" }
id = { name = "rg-lz-${local.r.name}-id-cc" }
nw = { name = "NetworkWatcherRG" } # Module docs recommend managing this
}
network_security_group_enabled = true # landingzones' Deny-Subnet-Without-Nsg requires subnets to have an NSG
network_security_groups = {
app = { name = "nsg-snet-app-${local.r.name}-cc", resource_group_key = "net" }
}
virtual_network_enabled = true
virtual_networks = {
spoke = {
name = "vnet-spoke-${local.r.name}-cc"
resource_group_key = "net"
address_space = [local.r.network.address_space]
hub_peering_enabled = true
hub_network_resource_id = var.hub_vnet_id
subnets = {
app = {
name = "snet-app"
address_prefixes = [local.r.network.app_subnet]
network_security_group = { key_reference = "app" }
}
}
}
}
user_managed_identities = {
deploy = {
name = "id-lz-${local.r.name}-deploy"
resource_group_key = "id"
role_assignments = {
rg_contrib = { definition = "Contributor", relative_scope = "/resourceGroups/rg-lz-${local.r.name}-net-cc" }
}
federated_credentials_github = {
env = { organization = local.r.github.organization, repository = local.r.github.repository,
entity = "environment", value = local.r.github.environment }
}
}
}
role_assignment_enabled = true
role_assignments = {
team_reader = { principal_id = local.r.owner_group_object_id, definition = "Reader", principal_type = "Group" }
}
budget_enabled = true
budgets = {
monthly = {
name = "budget-${local.r.name}-monthly"
amount = local.r.budget_monthly
time_grain = "Monthly"
time_period_start = "2026-12-01T00:00:00Z"
time_period_end = "2027-11-30T23:59:59Z"
notifications = {
actual80 = { enabled = true, operator = "GreaterThan", threshold = 80, threshold_type = "Actual", contact_emails = local.r.budget_contacts }
fcast120 = { enabled = true, operator = "GreaterThan", threshold = 120, threshold_type = "Forecasted", contact_emails = local.r.budget_contacts }
}
}
}
}
output "subscription_id" { value = module.lz.subscription_id }
cd vending terraform init -backend-config="storage_account_name=$ST_IAC" -backend-config="key=vending/myapp-dev.tfstate" terraform plan -out tfplan -var request_file=../requests/myapp-dev.yaml \ -var hub_vnet_id=$(az network vnet show -g rg-alz-conn-cc -n vnet-hub-cc --subscription $SUB_CONN --query id -o tsv)
Plan: 1x to add, 1 to change, 0 to destroy. # module.lz.module.subscription[0].azapi_resource.subscription_management_group_association[0] will be created # module.lz.module.virtualnetwork[0]...hub_peering... will be created # module.lz.module.budget[0]...monthly will be created
Resource addresses are illustrative; follow the actual plan. With EA, change to subscription_alias_enabled = true, provide subscription_alias_name, subscription_billing_scope, and subscription_workload, and remove subscription_id.
Lab 5: Vend the myapp-dev landing zone using the existing-subscription mode (about 15 minutes, nearly free)
$SUB_APP into the corp management group (hour 4 should already have placed it there) and creates a VNet and peerings in it. If you have only one subscription, set hub_peering_enabled to false, and set management_group to the management group the subscription is currently in.requests/myapp-dev.yaml using the Commands tab. For owner_group_object_id, use the myapp team group you created in hour 3: az ad group show -g grp-myapp-team --query id -o tsv (use the group name you created in hour 3).az graph query -q "resources | where type =~ 'microsoft.network/virtualnetworks' | mv-expand p = properties.addressSpace.addressPrefixes | project name, subscriptionId, prefix = tostring(p)" -o table
python3 -I -c "import ipaddress,sys; a=ipaddress.ip_network('10.2.0.0/16'); used=[ipaddress.ip_network(x) for x in sys.argv[1:]]; print('OVERLAP' if any(a.overlaps(u) for u in used) else 'OK')" 10.0.0.0/16 10.1.0.0/16
Name SubscriptionId Prefix -------------------- --------------- ----------- vnet-hub-cc … 10.0.0.0/16 vnet-spoke-myapp-cc … 10.1.0.0/16 OK
terraform apply tfplan (about 3–5 minutes). Verify:
az network vnet peering list -g rg-alz-conn-cc --vnet-name vnet-hub-cc --subscription $SUB_CONN --query "[].{n:name,s:peeringState}" -o table
az identity federated-credential list -g rg-lz-myapp-dev-id-cc --identity-name id-lz-myapp-dev-deploy --subscription $SUB_APP --query "[].subject" -o tsv
az consumption budget list --subscription $SUB_APP --query "[].{name:name,amount:amount}" -o table
N S ---------------------------------------- --------- peer-hub-to-myapp Connected <module-generated-name> Connected repo:contoso/myapp:environment:dev Name Amount ----------------------- -------- budget-myapp-dev-monthly 200.0
budget_monthly in the request file to 300, then plan again. Only 1 in-place update should appear. This is the “change the parameters and rerun” path.terraform destroy deletes the resources the module created and the management group association. The subscription leaves corp and returns to the tenant's default management group; move it back into corp later if hour 4 needs it. It does not cancel the subscription. Confirm that the plan shows no destruction of the subscription alias before you run it.Case 1: 200 subscriptions sharing one state
Problem: To save effort early on, all vending requests were placed in a single for_each. One change that switched the map keys from display name to alias made the plan show 180 peerings and budgets being replaced. Fix: Migrate to one state per subscription. For each request, run terraform state mv, or take it over with import blocks in the new configuration (use the actual module resource addresses). After that, the pipeline runs each one separately with key=vending/<name>.tfstate.
Case 2: Hub peering returns 403 partway through vending
Problem: The subscription, resource groups, and spoke were all created, but the hub-side peering failed with AuthorizationFailed. Cause: The vending identity has no Network Contributor role on the hub resource group in connectivity. Fix: Grant the missing permission and rerun the same apply. Resources that already exist are in state, so they are not created again. Nobody needs to roll back the subscription. Prevention: Write the vending identity's permission list into the platform identity baseline (hour 3).
Case 3: A startup with no EA
Problem: A pay-as-you-go account cannot create subscriptions through the API. Fix: Finance creates the subscription manually in the portal and files a ticket. The ticket automatically generates the request file (subscription_alias_enabled = false + subscription_id), and everything else is automated. After an MCA is signed, switch to alias mode by changing only two or three fields.
Common errors and fixes
(VnetAddressSpacesOverlap) Cannot create or update peering … address space overlaps
Cause: The requested address overlaps the hub or an already-peered spoke. Prevention: Validate in the PR using Resource Graph or IPAM, or let AVNM allocate the range with ipam_pools. Fix: Change the address in the request file and rerun. This is cheapest when the spoke has no workloads yet.
Subscription alias creation failed: the caller lacks permission to create subscriptions on this billing scope (check the actual error text)
Cause: The vending identity lacks the creator role on the EA enrollment account or the MCA invoice section. Fix: Grant it with Grant-SubscriptionCreatorRole (ALZ module), or use the enrollmentAccountRoleAssignments API as described in the official docs. EA grants must use 2019-10-01-preview.
AuthorizationFailed … Microsoft.Network/virtualNetworks/virtualNetworkPeerings/write … vnet-hub-cc
Cause: The hub-side peering is created by the vending identity, which needs Network Contributor on the hub. Fix: Grant the role, then rerun apply.
RequestDisallowedByPolicy … Deny-Subnet-Without-Nsg (landingzones)
Cause: The subscription has already been placed in corp and inherits the landingzones policy, but the subnet in the request has no NSG. Fix: Enable network_security_group_enabled in the module and have the subnet reference the NSG. This shows why the order “place first, then create resources” lets policy take effect during vending.
First operation on a new subscription fails with SubscriptionNotFound / resource provider not registered
Cause: The new subscription is not yet fully visible in ARM. Fix: Increase wait_for_subscription_before_subscription_operations.create, and keep resource provider registration enabled.
1. Without the module, use the CLI to create a production subscription named sub-lz-online-shop-prod under the EA enrollment account.
az extension add --name account az extension add --name alias az account alias create --name sub-lz-online-shop-prod \ --billing-scope "/providers/Microsoft.Billing/billingAccounts/<ba>/enrollmentAccounts/<ea>" \ --display-name sub-lz-online-shop-prod --workload Production az account alias show --name sub-lz-online-shop-prod --query properties
2. List all subscriptions under the corp management group, and confirm that the new subscription has been placed.
az account management-group subscription show-sub-under-mg --name corp -o table
Design an automated validation checklist for vending PRs, with the goal that the apply stage almost never fails.
① Validate the request file against a JSON Schema (required fields, workload allowed only as Production / DevTest, management group allowed only as corp / online / sandbox). ② Naming rules (CAF abbreviation + workload + environment + region) and length. ③ Address: no overlap with existing prefixes in IPAM or Resource Graph, and inside the regional pool. ④ Budget amount within the cost center's allowance. ⑤ The GitHub repository and environment exist. ⑥ The owner group exists in Entra. ⑦ terraform plan contains only the expected resource types and no destruction. ⑧ For corp requests, check whether public-facing resources are requested (corp's Deny policies will reject them).
Verified training videos
Official documentation
- Subscription vending implementation guidance
- CAF: Subscription vending
- Terraform Registry: avm-ptn-alz-sub-vending
- Bicep: avm/ptn/lz/sub-vending
- Programmatically create EA subscriptions
Video storyboard script (about 90 seconds)
This courseware cannot generate video or MP3 directly. A storyboard and narration script are provided for a video tool to use.
On screen: The application team submits a form in the portal, and the form turns into a YAML file that flies into a PR.
Narration: The application team only submits requirements. The platform pipeline handles everything else.
On screen: The checks on the PR tick off one by one: schema, IP, budget. After the merge, CD waits for approval.
Narration: Any error that can be caught in the PR must never be left until apply.
On screen: The new subscription card drops into the corp management group, and the policy icon lights up at once. Lines connect the spoke and the hub. A budget gauge appears.
Narration: Place first, then create resources, and policy takes effect from the first second.
Module 6 · Policy as Code: EPAC and the policy lifecycle
- Explain EPAC's desired state: under
deploymentRootScope, the repository is the source of truth. Explain howfullandownedOnlydiffer indesiredState.strategy, and howpacOwnerIdmarks ownership. - Write a
global-settings.jsonc(pacEnvironments), one assignment file (nodeName/definitionEntry/assignment/scope), and one exemption file with an expiry date. - Run three steps in order:
Build-DeploymentPlans→Deploy-PolicyPlan→Deploy-RolesPlan, and give each of the three steps its own least-privilege identity. - Decide how EPAC and avm-ptn-alz / Bicep divide the work, so the two tools do not fight over the same assignments. Know what
New-ALZPolicyDefaultStructureandSync-ALZPolicyFromLibraryare for.
What: what EPAC is
Enterprise Azure Policy as Code (EPAC) is an open-source PowerShell solution maintained by Microsoft employees (module EnterprisePolicyAsCode, version 11.5.12, released 2026-11-16). It uses JSON / JSONC / CSV files to declare policy definitions, policy sets, assignments, and exemptions, plus the role assignments that DINE and Modify need, and deploys them in dependency order. It can run in any CI/CD system that can run PowerShell. The project provides starter pipelines for Azure DevOps, GitHub Actions, and GitLab, and it can also be run manually.
Directory / file (Definitions/) | Contents |
|---|---|
global-settings.jsonc | pacOwnerId (a GUID that marks the resources deployed from this repository) and pacEnvironments: for each environment, pacSelector, cloud, tenantId, deploymentRootScope, managedIdentityLocation, globalNotScopes, and desiredState |
policyDefinitions/, policySetDefinitions/ | Custom definitions and policy sets (deployed at deploymentRootScope) |
policyAssignments/ | Assignment tree: nodeName, definitionEntry (policyName / policySetName / policyId …), assignment (name must be 24 characters or fewer at management group scope), parameters, enforcementMode, scope (scopes listed per pacSelector), and children (child nodes inherit and can override) |
policyExemptions/<pacSelector>/ | Exemptions (JSON or CSV): name, exemptionCategory, expiresOn, scopes, policyAssignmentId, policyDefinitionReferenceIds. If an environment folder is missing, EPAC does not manage exemptions for that environment. |
Output/ | Plan files policy-plan.json and roles-plan.json (pipeline artifacts) |
How: two phases (really three steps)
- Build-DeploymentPlans reads the repository and the current state in Azure, calculates the differences (create / update / replace / delete), and outputs two plans. The plans can be shown in the PR (capture the output with
$epacInfoStream).-DevOpsTypelets the pipeline decide whether the later stages run based on whether anything changed.-BuildExemptionsOnlyis a fast path for exemptions only.-AutoUpgradeMajorVersionsplans a major-version upgrade for built-in definitions that do not declare adefinitionVersion. - Deploy-PolicyPlan deploys definitions, then policy sets, then assignments, then exemptions, in dependency order, and deletes the objects the plan marks for deletion.
- Deploy-RolesPlan creates role assignments for assignments that use a managed identity, and cleans up any that are no longer needed.
| Step | Recommended identity | Role (scope) |
|---|---|---|
| Plan | One shared by all environments | Reader (tenant root) |
| Policy deployment | One per EPAC environment | Resource Policy Contributor (environment root) |
| Role deployment | One per EPAC environment | Role Based Access Control Administrator + policyAssignments/read (environment root). Consider a condition that blocks granting Owner, UAA, or RBAC Admin. |
If assignments use a user-assigned managed identity, the policy deployment and role deployment identities also need Managed Identity Operator (or the equivalent assign permission). Official hardening guidance: main requires a PR; add an approval between the plan and the deployment; optionally add another approval between the policy deployment and the role deployment.
Why: desired state, ownership, and “deduplication”
- full: EPAC manages the policy resources under
deploymentRootScopeand its child scopes, including all of them. Anything not in the repository is deleted, including anything someone created in the portal. This suits a mature setup, and it guarantees there are no shadow assignments. - ownedOnly: Manages only the resources defined in the repository and does not delete anyone else's. This suits a transition period (the official guidance is to move to full after a few weeks) or shared-responsibility setups.
- Ownership marker: EPAC writes
deployedBy(defaultepac/<pacOwnerId>/<pacSelector>) andpacOwnerIdinto the metadata, which tells “deployed by me” apart from “deployed by someone else”. Two EPAC repositories must use differentpacOwnerIdvalues, or they will delete each other's resources. - Exclusions and exceptions:
excludedScopes,excludedPolicyAssignments(supports wildcards),keepDfcSecurityAssignments(whether to keep the assignments Defender for Cloud creates automatically),cleanupObsoleteExemptions, anddoNotDisableDeprecatedPolicies. - Drift: If someone changes an EPAC-managed assignment in the portal, the next plan shows Update, and deployment changes it back to the value in the repository.
When: how EPAC and ALZ IaC divide the work
| Pattern | Approach | Best for |
|---|---|---|
| A: ALZ policy is deployed by avm-ptn-alz / Bicep, and EPAC only manages the organization's custom policy | EPAC strategy = ownedOnly (or full + excludedPolicyAssignments listing the ALZ assignment names). The assignment names on the two sides must not overlap. | Platform team leads, governance team supplements |
| B: All policy is managed by EPAC | Terraform or Bicep creates only the management groups and resources. ALZ policy structure files are generated with New-ALZPolicyDefaultStructure -Type ALZ (management group mapping, default enforcement mode, default parameters), then synced with Sync-ALZPolicyFromLibrary (EPAC 10.9.0 minimum). Use -Tag platform/alz/<version> to pin the library version. | Governance team is independent, has many policies, and spans multiple tenants |
| Not recommended | Two tools deploying the same assignment name | The result depends on which tool runs last. Full mode can also delete each other's assignments. |
- “EPAC and Terraform Policy are the same thing.” They are not. Terraform Policy / OPA checks whether the IaC plan is compliant. EPAC deploys the Azure Policy resources themselves.
- “ownedOnly is safer, so I'll always use it.” It does not clean up shadow assignments, so unowned policies build up over time.
- “If an exemption is in the repository, it lasts forever.” Set
expiresOn. After it expires, the object is kept but no longer applies (hour 2), and EPAC can clean it up in a later run. - “Deploy-PolicyPlan has already granted permissions to the DINE managed identity.” It has not. Granting permissions is the job of
Deploy-RolesPlan, and it uses a different identity.
EPAC pipeline and identities
EPAC planner: the same set of changes gives different plans under full and ownedOnly
The left side shows the repository changes in this PR and the current state in Azure. Choose a strategy and settings, click “Generate plan”, and watch how Build-DeploymentPlans classifies each object. Then click “Deploy” to see the three steps run. The logic follows EPAC's desired-state documentation. The output is an example.
Core commands
| Command | Purpose |
|---|---|
Build-DeploymentPlans -PacEnvironmentSelector epac-dev [-DetailedOutput] | Generate plans to ./Output |
Deploy-PolicyPlan -PacEnvironmentSelector epac-dev | Deploy definitions, policy sets, assignments, and exemptions |
Deploy-RolesPlan -PacEnvironmentSelector epac-dev | Grant permissions to the managed identities |
Export-AzPolicyResources | Export existing policy resources in EPAC format (the starting point for moving into EPAC) |
New-PipelinesFromStarterKit -PipelineType GitHubActions|AzureDevOps -BranchingFlow GitHub|Release -ScriptType module | Generate a pipeline from the starter package |
New-ALZPolicyDefaultStructure / Sync-ALZPolicyFromLibrary | Bring ALZ library policy into EPAC |
global-settings.jsonc
{
"$schema": "https://raw.githubusercontent.com/Azure/enterprise-azure-policy-as-code/main/Schemas/global-settings-schema.json",
"pacOwnerId": "<new-guid>",
"pacEnvironments": [
{
"pacSelector": "epac-dev",
"cloud": "AzureCloud",
"tenantId": "<tenant-id>",
"deploymentRootScope": "/providers/Microsoft.Management/managementGroups/epac-dev",
"desiredState": { "strategy": "full", "keepDfcSecurityAssignments": false },
"managedIdentityLocation": "canadacentral"
}
]
}
Assignment: Allowed locations (Audit)
// Definitions/policyAssignments/allowed-locations.jsonc
{
"$schema": "https://raw.githubusercontent.com/Azure/enterprise-azure-policy-as-code/main/Schemas/policy-assignment-schema.json",
"nodeName": "/Governance/",
"definitionEntry": { "policyName": "e56962a6-4747-49cd-b67b-bf8b01975c4c", "displayName": "Allowed locations" },
"assignment": { "name": "allowed-loc-lab", "displayName": "Allowed locations (lab)", "description": "hour 6 EPAC lab" },
"enforcementMode": "Default",
"parameters": { "listOfAllowedLocations": [ "canadacentral", "canadaeast" ], "effect": "Audit" },
"scope": { "epac-dev": [ "/providers/Microsoft.Management/managementGroups/epac-dev" ] }
}
Exemption: time-limited and auditable
// Definitions/policyExemptions/epac-dev/lab-exemptions.jsonc
{
"$schema": "https://raw.githubusercontent.com/Azure/enterprise-azure-policy-as-code/main/Schemas/policy-exemption-schema.json",
"exemptions": [
{
"name": "exm-dr-test-eastus",
"displayName": "DR test may use eastus until 2026-12-31",
"description": "CHG-1234 approved by governance board",
"exemptionCategory": "Waiver",
"expiresOn": "2026-12-31T23:59:59Z",
"scopes": [ "/subscriptions/<app-sub-id>/resourceGroups/rg-dr-test-cc" ],
"policyAssignmentId": "/providers/Microsoft.Management/managementGroups/epac-dev/providers/Microsoft.Authorization/policyAssignments/allowed-loc-lab"
}
]
}
Build-DeploymentPlans -PacEnvironmentSelector epac-dev -DefinitionsRootFolder ./Definitions -OutputFolder ./Output Get-ChildItem ./Output -Recurse -Filter *-plan.json | Select-Object FullName
Policy Assignments: 1 new, 0 update, 0 replace, 0 delete, 0 unchanged Policy Exemptions: 1 new, 0 update, 0 delete Role Assignments: 0 add, 0 remove FullName -------- /home/me/epac/Output/plans-epac-dev/policy-plan.json
The output format is an example (the output style in EPAC 11 is more modern). The subdirectory that holds the plan files depends on your setup.
Lab 6: Run EPAC end to end on a separate epac-dev management group (about 15 minutes, free)
az account management-group create --name epac-dev --display-name "EPAC Dev" \ --parent $(az account show --query tenantId -o tsv) # Optional: temporarily place a lab subscription in it so you can see compliance results az account management-group subscription add --name epac-dev --subscription $SUB_APP
global-settings.jsonc under ~/epac/Definitions (generate pacOwnerId with [guid]::NewGuid()), plus the assignment and exemption files. If no subscription has been placed yet, delete the exemption file first.Set-Location ~/epac Build-DeploymentPlans -PacEnvironmentSelector epac-dev Deploy-PolicyPlan -PacEnvironmentSelector epac-dev Deploy-RolesPlan -PacEnvironmentSelector epac-dev # This assignment is Audit, so no roles are needed; run the step anyway az policy assignment show -n allowed-loc-lab --scope /providers/Microsoft.Management/managementGroups/epac-dev --query metadata
{
"deployedBy": "epac/<pacOwnerId>/epac-dev",
"pacOwnerId": "<pacOwnerId>"
}allowed-loc-lab to DoNotEnforce. Then create an assignment by hand: az policy assignment create -n team-x-manual --policy 871b6d14-10aa-478d-b590-94f262ecfa99 --scope /providers/Microsoft.Management/managementGroups/epac-dev -p '{"tagName":{"value":"costCenter"}}'. Run Build-DeploymentPlans again. With full, you should see 1 update (revert) and 1 delete (the shadow assignment). Change the strategy to ownedOnly and plan again, and the delete disappears.New-ALZPolicyDefaultStructure -DefinitionsRootFolder ./Definitions-alz -Type ALZ -Tag "platform/alz/2026.11.0" # Edit the files generated under Definitions-alz/policyStructures: management group mapping, enforcementMode, default parameters # Sync-ALZPolicyFromLibrary -DefinitionsRootFolder ./Definitions-alz -Type ALZ -PacEnvironmentSelector epac-dev -Tag "platform/alz/2026.11.0"Review
management_group_function and defaultParameterValues in the structure files. Understand that they are the same concept as policy_default_values in avm-ptn-alz. Do not deploy the sync result to the alz tree that Terraform already manages.az account management-group subscription remove --name epac-dev --subscription $SUB_APP (the subscription returns to the default management group, then move it back to corp), and az account management-group delete --name epac-dev.Case 1: The first run in full mode deleted the Defender assignments
Problem: A team pointed full directly at the tenant root. The plan showed dozens of deletions, including the security baseline assignments that Defender for Cloud creates automatically. The reviewer did not look closely and approved it. Fix: The standard order for moving into EPAC: Export-AzPolicyResources to export the current state, run ownedOnly for a few weeks, gradually bring the exported assignments into the repository, set keepDfcSecurityAssignments and excludedScopes, then switch to full. In approvals, treat the number of deletions as the red line.
Case 2: Exemptions became a permanent back door
Problem: An audit found that 60% of the exemptions had no expiry date. Fix: Validate in CI that every exemption file has an expiresOn no more than 180 days out and that its description includes a change ticket number. Enable cleanupObsoleteExemptions to remove exemptions that point to deleted assignments. Use the fast path -BuildExemptionsOnly for exemptions, so you do not have to wait for a full policy deployment just to change an exemption.
Case 3: Two EPAC repositories deleting each other's resources
Problem: The security team and the platform team each had an EPAC repository. They copied the same global-settings.jsonc (with the same pacOwnerId), and both used full on the same root. As a result, each run deleted the other's assignments. Fix: Give each repository its own pacOwnerId. Split the roots by scope, or set one side to ownedOnly. When one repository references the other's definitions, use excludedPolicyDefinitions.
Common errors and fixes
The plan shows a large number of unexpected Deletes
Cause: The strategy is full, and there are assignments under the root scope that are not in the repository (created by hand in the portal, by other tools, or by Defender). Fix: Switch to ownedOnly first. Exclude them with excludedPolicyAssignments, excludedScopes, or keepDfcSecurityAssignments, or export them and bring them into the repository.
Policy assignment name … exceeds the maximum length (management group scope)
Cause: At management group scope, an assignment name can be at most 24 characters (64 for subscriptions and resource groups). Fix: Shorten assignment.name. The display name can stay long.
DINE assignment deployed successfully but remediation failed: the managed identity lacks permissions
Cause: Only Deploy-PolicyPlan was run, not Deploy-RolesPlan, or the role deployment identity is missing RBAC Administrator. Fix: Run the role step, and check roles-plan.json.
pacSelector … not found in global-settings
Cause: The selector spelling is inconsistent (all lowercase is recommended), or DefinitionsRootFolder points to the wrong place (default $env:PAC_DEFINITIONS_FOLDER or ./Definitions). Fix: Standardize the pacSelector, and pass the path explicitly in the pipeline.
The same ALZ assignment keeps being changed back and forth by the Terraform plan and the EPAC plan
Cause: Two tools manage the same assignment name. Fix: Pick one owner (pattern A or B). On the other side, exclude that assignment or remove its declaration.
1. Generate and deploy a plan for exemptions only (the fast path).
Build-DeploymentPlans -PacEnvironmentSelector tenant -BuildExemptionsOnly Deploy-PolicyPlan -PacEnvironmentSelector tenant
2. Find all assignments under epac-dev that were not deployed by this EPAC repository.
az policy assignment list --scope /providers/Microsoft.Management/managementGroups/epac-dev \
--query "[?metadata.pacOwnerId!='<pacOwnerId>'].{name:name,by:metadata.createdBy}" -o tableThe company has already deployed ALZ using the Terraform starter code. The governance team wants to bring 30 organization custom policies under EPAC management, and requires that any assignment made by hand in the portal be removed. How would you design this?
Use pattern A. ALZ default policy stays managed by avm-ptn-alz. Set EPAC's deploymentRootScope to the intermediate root alz. Start with strategy ownedOnly as a transition, then switch to full and list the ALZ assignment names in excludedPolicyAssignments (you can generate the list from the assignment files in .alzlib). Exclude the ALZ definitions with excludedPolicyDefinitions, and keep keepDfcSecurityAssignments as needed. Give the organization's policy assignment names a common prefix (such as org-) so they are easy to tell apart. Keep EPAC's three identities separate from the Terraform plan and apply identities. Both pipelines show their plans in the PR, and any change by one side to an object owned by the other is treated as a configuration error.
Verified training videos
Official documentation
Video storyboard script (about 90 seconds)
This courseware cannot generate video or MP3 directly. A storyboard and narration script are provided for a video tool to use.
On screen: Repository files and the assignments in Azure sit side by side, connected one to one. A manually created portal assignment has no connection and blinks.
Narration: EPAC treats the repository as the desired state. The plan is the difference between the two.
On screen: Switching between full and ownedOnly. The blinking assignment is marked for deletion under full and kept under ownedOnly.
Narration: full cleans up every shadow assignment. ownedOnly manages only its own.
On screen: Three identities take the stage in turn: Reader generates the plan, Policy Contributor deploys the assignments, and RBAC Admin grants permissions to the managed identity.
Narration: Three steps, three identities, least privilege.
Module 7 · Version upgrades and policy refresh
- List the version layers you need to track separately: the library tag, the alz provider, avm-ptn-alz and other pattern modules, the starter code, Bicep AVM modules, built-in definition versions, and EPAC. Know that the Bootstrap itself cannot be upgraded, and that azurerm 5.x is not yet supported.
- Follow the official upgrade guide once: read the release notes → change the version on a branch → diff against the upstream starter code → PR plan → non-production → production → remediation tasks.
- Read the typical changes in an upgrade plan: new policy sets with date suffixes, deprecated definitions, changed default values for assignment parameters, and rebuilt role assignments.
- Explain the key points of the two migration paths. caf-enterprise-scale → AVM: use import blocks with terraform-state-importer, or build the hierarchy anew. Classic ALZ-Bicep → AVM Bicep: converge in place, align identities, and handle
InvalidPolicyParameterUpdatein stages.
What: the version layers to track (2026-11-18)
| Layer | Current version | Where to change | Cadence |
|---|---|---|---|
| ALZ library (calendar versioning) | platform/alz/2026.11.0 (2026-11-06); previous version 2026.10.0 (2026-10-05) | Terraform: the ref in lib/alz_library_metadata.json. Bicep: tooling/alz_library_metadata.json + library JSON + Update-AlzLibraryReferences.ps1. EPAC: -Tag | About monthly |
| alz provider | 0.22.1 (2026-11-03) | terraform.tf (the starter code constraint is ~> 0.21) | Irregular |
| avm-ptn-alz | 0.23.0 (2026-11-18) | main.management.groups.tf (starter code v17.7.0 is still at 0.21.0) | About every 1–2 months |
| avm-ptn-alz-management | 0.10.0 (2026-10-27) | main.management.resources.tf | Irregular |
| Terraform starter code | v17.7.0 (2026-11-06) | Merge manually after diffing against upstream | Monthly |
| Bicep starter code / AVM modules | v2.5.0; avm/ptn/alz/empty 0.3.6 | br/public:…:<version> in the templates | Monthly |
| Bootstrap | bootstrap-modules v7.3.2 | Not upgradable (one-time) | — |
| azurerm | Latest is 5.14.0, but the starter code requires ~> 4.0 | Do not upgrade to 5.x | — |
| Built-in definition versions | definitionVersion of assignments (such as 2.*.*) | Assignment files in the library; EPAC can use -AutoUpgradeMajorVersions | Released with built-in policy |
| EPAC | 11.5.12 (2026-11-16) | Module version installed by the pipeline | Frequent |
How: the official upgrade process (Terraform starter code)
- Read the release notes: the library's Releases (
platform/alz/*), the avm-ptn-alz Releases, the starter code Releases, and the Accelerator's “Release Notes” page (which lists only the breaking changes that require action, for example v17.0.0 adds thelocalmanagement group). - Change the version: in your branch, update
refand the moduleversion. The official recommendation is to pin exact versions (or use~> 0.23.0to accept patch updates only). - Compare with upstream code: clone
alz-terraform-accelerator, copy the latesttemplates/platform_landing_zone/*.tfinto your repo and diff them. Usecode --diffto compare your tfvars with the upstreamexamples/…/*.tfvars, and add any new configuration structures. - PR plan: focus on destroy and replace. For policy changes, check each one against the release notes.
- Merge → CD plan → approval → apply. Rehearse first in a non-production tenant (or a separate alz tree).
- Remediation: newly added DINE and Modify assignments take effect automatically only on new resources. Existing resources need remediation tasks (hour 2, Module 5).
Why: why policies need to be “refreshed”
- New policy sets get new names: membership changes may require different managed identity roles or parameters, so the library publishes new policy sets with a date suffix (for example
Enforce-Guardrails-Automation_20260910). The old ones are markeddeprecated: true, withsupersededBypointing to the new name. On upgrade, assignments switch to the new definitions, and the old definitions are cleaned up afterward. - Default value changes: for example, 2026.11.0 changes the default category of
Deploy-Diag-LogsCatfrom audit to allLogs. Log volume and cost go up (see hour 5). - Compliance requirements change: the Microsoft cloud security benchmark, TLS and zero-trust guardrails are updated continuously. Staying on an old library means staying on an old baseline.
When: migrating legacy implementations
| From | To | Key points |
|---|---|---|
Azure/caf-enterprise-scale/azurerm (deprecated; repo archived 2026-09-15) | avm-ptn-alz + management and connectivity AVM modules | Two paths: ① migrate the management and connectivity resources; ② migrate the management groups and policies. Do ① first, then ②. The tool Azure/terraform-state-importer helps generate import blocks, in three stages: prepare → map resource IDs and generate import blocks → adjust attributes until the plan shows no changes. Alternative: follow the brownfield guide to build a new management group hierarchy, then move subscriptions into it. |
| Classic ALZ-Bicep (removed from the Accelerator 2026-02-16; archived 2027-02-16) | alz-bicep-accelerator (AVM) | Bicep has no state, so no import is needed: converge in place. Make the AVM configuration produce the same names and IDs as the existing environment, and ARM updates rather than creates. The classic setup uses nested MG IDs (<prefix>-landingzones-corp), while AVM defaults to a flat layout (corp). Log resource names also differ (classic alz-log-analytics, AVM default law-alz-<loc>). A hard blocker is InvalidPolicyParameterUpdate. Handle it in stages: delete assignments → delete policy sets → delete definitions → fresh deployment. The stages can be rerun. A network migration guide is not yet available. |
Azure/lz-vending/azurerm (no longer updated after 7.0.3) | Azure/avm-ptn-alz-sub-vending/azure | The new module is based on AzAPI and has different input structures. Migrate one subscription at a time, with one state per subscription, and use import to take over existing peerings, budgets and so on. Resource addresses follow the new module's plan. |
- “Upgrading everything to the latest version at once is the easiest.” Upgrade one layer at a time so that plan changes can be attributed. Keep library and module changes in separate PRs.
- “If what-if shows Modify, the deployment will succeed.” Updates that remove policy parameters are rejected (
InvalidPolicyParameterUpdate), and what-if cannot catch this. - “Upgrading avm-ptn-alz also upgrades the starter code.” The starter code is copied into your repo, so you need to compare it against the upstream diff yourself.
- “Rerunning Bootstrap gives you new pipeline templates.” Bootstrap does not support upgrades. Port any needed changes to the template repo by hand.
Upgrade timeline: one small PR per month
ALZ-Bicep classic migration: converge in place
Upgrade impact analyzer
Tick the changes this PR will make, then click “Run plan”. The analyzer infers, from the official release notes and upgrade guide, the types and risks of changes that will show up in the plan. Counts are illustrative, not a real plan.
Core commands
| Command | Purpose |
|---|---|
git ls-remote --tags https://github.com/Azure/Azure-Landing-Zones-Library.git 'platform/alz/*' | List all ALZ tags in the library |
git diff --stat platform/alz/2026.10.0 platform/alz/2026.11.0 -- platform/alz | Files changed between two library versions |
terraform init -upgrade | Upgrade providers and modules within constraints, and update the lock file |
az policy set-definition list --management-group alz --query "[?metadata.deprecated]" | Find deployed but deprecated policy sets |
az policy remediation create … | Remediate existing resources for the DINE and Modify assignments added by the upgrade |
1) Compare two library versions
git clone -q --filter=blob:none https://github.com/Azure/Azure-Landing-Zones-Library.git alzlib && cd alzlib git diff --stat platform/alz/2026.10.0 platform/alz/2026.11.0 -- platform/alz | tail -5 git diff platform/alz/2026.10.0 platform/alz/2026.11.0 -- platform/alz/policy_assignments/Deploy-Diag-LogsCat.alz_policy_assignment.json
platform/alz/policy_assignments/Deploy-Diag-LogsCat.alz_policy_assignment.json | 4 +- ... 2x files changed, 1xx insertions(+), 4x deletions(-) - "value": "audit" + "value": "allLogs"
2) Upgrade the Terraform starter code (the official guide's steps)
git clone https://url-to-your-repo ~/code/alz-mgmt; Set-Location ~/code/alz-mgmt git checkout -b upgrade-2026-11 # ① Library: edit the ref in lib/alz_library_metadata.json # ② Module: version = "0.23.0" in main.management.groups.tf git clone https://github.com/Azure/alz-terraform-accelerator ~/code/alz-terraform-accelerator $latest = "~/code/alz-terraform-accelerator/templates/platform_landing_zone" Copy-Item "$latest/*.tf" . -Force Copy-Item "$latest/modules/*" ./modules -Recurse -Force git diff --stat # review upstream changes, keep your customizations code --diff ./platform-landing-zone.auto.tfvars "$latest/examples/full-single-region/hub-and-spoke-vnet.tfvars" git add . ; git commit -m "Upgrade ALZ library 2026.11.0 and avm-ptn-alz 0.23.0" ; git push -u origin upgrade-2026-11
3) Track modules and providers with Dependabot (the library ref needs a separate script)
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: terraform
directory: "/"
schedule: { interval: weekly }
- package-ecosystem: github-actions
directory: "/"
schedule: { interval: weekly }
Dependabot's terraform ecosystem can detect new versions of Registry modules and providers, but it does not understand alz_library_metadata.json. Use a small script that runs weekly, calls git ls-remote to compare library versions, and opens a PR.
Lab 7: rehearse a library upgrade in the alz6 lab project (about 15 minutes; plan-only runs are free)
~/alz-lab/tf-alz from Module 2, change the ref in lib/alz_library_metadata.json to 2026.10.0. If you applied in Module 2, run terraform apply to return to the old version (do this only on a separate alz6 tree). Otherwise, just record the plan.platform/alz/2026.11.0 Release and list 3 changes you expect to see in the plan. Hints: diagnostic log categories, the delete-protection policy pattern, and a certain guardrail policy set.ref back to 2026.11.0, then run terraform plan -out tfplan | tee upgrade.txt.
grep -E 'will be (created|destroyed|updated in-place)|must be replaced' upgrade.txt | sed -E 's/.*# //' | sort | uniq -c | sort -rn | head
3 module.alz.azapi_resource.policy_definitions[...] will be updated in-place 1 module.alz.azapi_resource.policy_assignments["alz6/Deploy-Diag-LogsCat"] will be updated in-place 1 module.alz.azapi_resource.policy_set_definitions[...] will be created
version from 0.23.0 to an earlier version and then back, to see why “one layer per PR” matters. Read the 0.23.0 breaking-change notes (random UUID lifecycle).tfplan and upgrade.txt from the plan-only runs. Keep applied labs at 2026.11.0.Case 1: no upgrades for two years, then 20 library versions at once
Problem: the plan showed over 300 changes, too many to review one by one, so the team gave up. Approach: upgrade one version per month, with one PR per version, applied to a non-production tenant first. The team caught up in six weeks. Afterward, a weekly version-check script and a monthly upgrade meeting keep a steady rhythm.
Case 2: caf-enterprise-scale migration only half done
Problem: the team migrated the management groups and policies first (path ②) but not the connectivity resources. The private DNS zone ID needed by the new assignments was still in the old state, so the two configurations referenced each other. Approach: follow the official order: migrate the management and connectivity resources first (path ①), then the management groups and policies. Freeze other changes on both sides during the migration.
Case 3: classic Bicep migration, what-if looked fine, but the deployment failed
Problem: what-if showed every custom definition as Modify, but the actual deployment failed with InvalidPolicyParameterUpdate. Cause: the new library version's definition removed a parameter. Azure does not allow a parameter to be removed in place, and what-if does not check for this. Approach: the officially supported method. Delete the classic assignments, policy sets and definitions from the bottom up, then let AVM create everything fresh. Because management group deployments are not atomic, the script must be rerunnable. Policies will be briefly missing during this time, so schedule a change window.
Common errors and fixes
No available releases match the given constraints … hashicorp/azurerm
Cause: a module or the root module requires azurerm 5.x, which conflicts with the starter code's ~> 4.0. Fix: keep ~> 4.0. Do not upgrade a module alone if it pulls in 5.x.
After the upgrade, the plan shows that all management groups must be destroyed and recreated
Cause: the management group ID changed (a custom architecture definition was overwritten), or a module resource address changed without a moved block. Fix: check the architecture definitions in lib. The starter code's outputs.moved.tf and variables.moved.tf, and the moved blocks after the module calls, must be updated together with upstream.
InvalidPolicyParameterUpdate: policy parameters cannot be removed during policy update
Cause: the new version's custom definition removed or renamed a parameter. Fix: rebuild in stages (delete assignments → delete policy sets → delete definitions → redeploy). In Terraform, the module can handle this as a replacement, or you can delete the resources by hand in a maintenance window before applying.
After the upgrade, many resources show as non-compliant, but the remediation tasks did not run automatically
Cause: new DINE and Modify assignments take effect at request time only for new resources. Existing resources need remediation tasks. Fix: az policy remediation create --policy-assignment … --resource-discovery-mode ReEvaluateCompliance (hour 2).
caf-enterprise-scale migration: Error: Resource already managed by Terraform / import failed
Cause: the same resource is still in the old state, or the import block's address does not match the new module's resource address. Fix: follow the migration guide and use terraform-state-importer to generate the mapping. Do not run apply on the old configuration until the migration is complete.
1. List the 5 most recent platform/alz tags in the library.
git ls-remote --tags --sort=-v:refname https://github.com/Azure/Azure-Landing-Zones-Library.git 'platform/alz/*' | head -5
2. Find all custom policy sets marked as deprecated under the alz management group.
az policy set-definition list --management-group alz \
--query "[?metadata.deprecated==\`true\`].{name:name,supersededBy:metadata.supersededBy}" -o tableDesign a “keep up to date” mechanism for a Terraform platform repo. It must be auditable and keep risk under control.
① A weekly script checks library tags and Registry versions, and opens a PR when a new version appears (Dependabot can handle modules and providers). ② Each PR changes only one layer. ③ CI generates a plan summary automatically, counted by create / update / replace / destroy, and requires a link to the matching release notes. ④ Apply first in a non-production tenant or a separate management group tree, and watch for 24 hours of deny events and compliance changes. ⑤ After the production apply, run remediation tasks for the new DINE assignments. ⑥ Compare against the upstream diff of the starter code once a month. ⑦ Record the current version of each layer and the next upgrade window in the platform repo README.
Verified teaching videos
Official docs
- Terraform Upgrade Guidance
- Migration from CAF Enterprise Scale (aka.ms/alz/tf/migrate)
- Migration from Classic (Bicep)
- Azure Landing Zones Library Releases
- CAF: Keep your Azure landing zone up to date
Storyboard for the video (about 90 seconds)
This courseware cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: on a calendar, one library version tag per month, next to a growing stack of “not upgraded” files.
Narration: the library is released every month. If you don't upgrade, the gap only gets harder to close.
Visual: three small PRs pass in turn: library, module, starter code.
Narration: one layer per PR, so every line of the plan can be traced to its source.
Visual: the classic Bicep and caf-enterprise-scale icons are stamped “Archived”, with an arrow pointing to AVM.
Narration: the old implementations have retired. The key to migration is getting the new code to recognize the old resources.
Module 8 · Six-hour recap, self-check and cleanup
- Map each object type from Hours 1–6 to “who manages it with which code”, and find the parts that are still maintained by hand.
- Complete the self-check across six dimensions, and go back to the matching hours and modules based on your results.
- Use the interactive troubleshooting tree to locate automation failures: Bootstrap, OIDC, state, authorization, policy updates, vending, stacks, EPAC.
- Clean up the lab resources created in this hour in the correct order, without deleting anything earlier hours still need.
What: six-hour knowledge map, from manual to code
| Hour | Core question | Output when managed by hand | Owner after hour 6 |
|---|---|---|---|
| Hour 1 | Why a landing zone is needed, and how to build the hierarchy | 12 management groups, first policy assignment | avm-ptn-alz (architecture definitions) or modules such as Bicep int-root |
| Hour 2 | Subscriptions, naming, policy effects, library | Custom definitions, assignments, exemptions, remediation tasks | ALZ library + policy_assignments_to_modify / archetype override. Organization policies are handed to EPAC. |
| Hour 3 | Identity and access | Custom roles, PIM, deployment identities and federated credentials | Platform identities are created by Bootstrap. Application deployment identities are created by the vending module. PIM still follows the identity governance process. |
| Hour 4 | Networking | hub, Firewall, DNS, spoke peering | Connectivity modules (hub-spoke / vWAN). Spokes and peering are created by the vending module. |
| Hour 5 | Management and monitoring | Log Analytics, AMA / DCR, alerts, budgets | Management resource modules + DINE policies. Subscription budgets are created by the vending module. |
| Hour 6 | Automation | Platform repo, pipelines, vending, EPAC, upgrade cadence | The Git repository itself (PR + approval + plan artifacts) |
Why: “every object has exactly one owner”
- Two tools managing the same object → drift, overwrites, and mutual deletion in full mode (Module 6, Case 3).
- An object no tool manages → shadow configuration. Audits cannot trace its origin, and it gets forgotten during upgrades.
- A person (rather than a pipeline) as the owner → you cannot prove that “what runs is what was approved” (Module 4).
How: self-check checklist (ready to use directly in a review)
| Dimension | Signs of meeting the bar | Review |
|---|---|---|
| Bootstrap and repository | Platform repo exists, main is protected, and the bootstrapper's temporary permissions were revoked after Bootstrap | Module 1 |
| IaC structure | Library and module versions pinned exactly; all customizations in lib and tfvars; no forked library | Modules 2, 3 |
| Pipeline | PR plan, apply approval, plan artifacts, OIDC subject bound to the environment, drift detection | Module 4 |
| Vending | One subscription, one file, one state; PR validates addresses; place first, then create resources; budgets | Module 5 |
| Policy lifecycle | Each assignment has one owner; exemptions have expiry dates; EPAC (if used) has three identities | Module 6 |
| Upgrade | Monthly, one layer per PR, non-production first, remediation tasks | Module 7 |
- “Cleanup is just running terraform destroy.” The platform landing zone involves subscription placement, role assignments for the policy managed identities, and Bootstrap's VCS objects. Getting the order wrong leaves orphaned role assignments, or leaves subscriptions outside the deleted management group.
- “Lab tenants don't need cleanup.” Resources billed by the hour (runners, NAT gateways, firewalls) and elevated access at the root must all be revoked.
Platform as code: the end state
Six-dimension self-check radar
Tick the items you meet in each dimension (3 per dimension). The radar chart updates in real time and suggests which modules to revisit. Results are kept only on this page and are not uploaded.
Cleanup order (start with what depends on others)
| # | Object | Command |
|---|---|---|
| 1 | Vending lab (myapp-dev) | terraform destroy (existing-subscription mode; does not cancel the subscription) |
| 2 | EPAC lab | Delete the definition files → plan / deploy; delete the epac-dev management group |
| 3 | Deployment stack lab | az stack group delete … --action-on-unmanage deleteAll |
| 4 | alz6 tree (if applied) | terraform destroy |
| 5 | Accelerator platform landing zone | Remove-PlatformLandingZone … -PlanMode, then remove -PlanMode after confirming |
| 6 | Bootstrap (VCS + bootstrap resources) | Deploy-Accelerator -Destroy (or add -destroy in advanced mode) |
| 7 | Manual lab state storage | az group delete -n rg-alz-iac-cc |
| 8 | Elevated access at the root | Turn off “Access management for Azure resources” in the Entra admin center, or delete the User Access Administrator assignment on / |
# 5) Accelerator platform landing zone (preview first) Remove-PlatformLandingZone ` -ManagementGroups "<root-parent-management-group-id>" ` -Subscriptions "<management-subscription-id>", "<connectivity-subscription-id>" ` -AdditionalSubscriptions "<bootstrap-subscription-id>" ` -PlanMode # If the platform subscriptions contain resource groups to keep (such as the hour 4 hub), keep them with -ResourceGroupsToRetainNamePatterns # 6) VCS and bootstrap resources (while the interactive-mode directory structure still exists) Deploy-Accelerator -Destroy
# 8) Revoke User Access Administrator on the root (the assignment created by elevated access)
az role assignment delete --assignee $(az ad signed-in-user show --query id -o tsv) \
--role "User Access Administrator" --scope "/"
az role assignment list --scope "/" --query "[].{who:principalName,role:roleDefinitionName}" -o table
Who Role ----- ---- (empty: no assignments for you remain at the root)
Lab 8: self-check + ordered cleanup (about 15 minutes)
pacOwnerId):
az graph query -q "policyresources | where type =~ 'microsoft.authorization/policyassignments' | extend md = properties.metadata | project name, scope = tostring(properties.scope), createdBy = tostring(md.createdBy), epac = tostring(md.pacOwnerId) | where isempty(epac)" --management-groups alz -o tableLabel the owner of each result: avm-ptn-alz, EPAC, Defender, or manual (needs action).
terraform plan -destroy, -PlanMode, EPAC plan).Case 1: during cleanup, the management group was deleted first, and subscriptions “fell” to the tenant root
Problem: someone deleted the alz management group tree directly in the test tenant. Dozens of subscriptions returned to the tenant root group, and all inherited policies disappeared. Approach: use Remove-PlatformLandingZone, or Terraform's subscription placement destroy behavior (subscription_placement_destroy_behavior), to decide explicitly where subscriptions go. Use PlanMode first.
Case 2: the self-check found that the “pipeline” dimension scored only 1 point
Problem: a team had a platform repo, but an engineer still ran apply from their own machine. Approach: fill the gaps as in Module 4: an apply environment, plan artifacts and OIDC. Remove local credentials, and manage emergency manual access with PIM (hour 3).
Case 3: shadow assignments from Defender
Problem: the inventory found more than ten assignments with no owner. Cause: Defender for Cloud creates them automatically when a plan is enabled. Approach: decide who manages them (the Deploy-MDFC-Config assignment in the library, or the keepDfcSecurityAssignments policy in EPAC), and record the decision in the platform documentation.
Interactive troubleshooting tree: automation failed, where do I start?
Answer the questions step by step to pinpoint the specific cause and command. Covers the common failures across all modules in this hour.
Extra: three general diagnostic actions
First, confirm who is running it
az account show --query "{user:user.name,type:user.type,tenant:tenantId}" -o json # local machine
# In a pipeline: print the identity that matches ARM_CLIENT_ID
az identity list --query "[?clientId=='$ARM_CLIENT_ID'].{name:name,rg:resourceGroup}" -o tableThen check the Entra sign-in logs and the activity log
Sign-in failures for workload identities appear under Entra's “service principal sign-ins” (managed identity sign-ins). Authorization failures appear in the subscription or management group activity log (az monitor activity-log list --status Failed).
Finally, check policy: was it denied by a Deny effect?
The error code RequestDisallowedByPolicy means a policy denied the request, and the message includes the assignment name. Tell it apart from RBAC's AuthorizationFailed and from a deny assignment error (Hours 2 and 3).
1. Preview the deletion of the Accelerator platform landing zone, but keep the resource group named rg-alz-conn-cc.
Remove-PlatformLandingZone -ManagementGroups "<root-parent-mg-id>" ` -Subscriptions "<mgmt-sub>", "<conn-sub>" ` -ResourceGroupsToRetainNamePatterns "rg-alz-conn-cc" -PlanMode
2. List all role assignments at the root scope "/", and confirm that the elevated access has been revoked.
az role assignment list --scope "/" -o table
You take over a “semi-automated” ALZ. The management groups and policies come from a 2024 portal accelerator, networking uses Terraform, and vending is done by hand through tickets. Provide a 90-day roadmap.
Days 1–30: inventory (list all assignments and their owners with Resource Graph), use the IaC Accelerator in a test tenant to generate target code, and decide between Terraform and Bicep. Build the platform repo and pipelines (OIDC, approvals, plan artifacts). Days 31–60: bring the management groups and policies under avm-ptn-alz (use a custom architecture to keep the existing IDs, and import where needed). Hand organization policies to EPAC, starting with ownedOnly. Move the networking code to connectivity modules, or keep a separate state and bring it under the same pipeline standard. Days 61–90: launch vending (start with existing-subscription mode, and switch to aliases once EA or MCA is in place), set up drift detection and a monthly upgrade cadence, and switch EPAC to full mode. Throughout: one owner per object, and rehearse every step in non-production first.
Verified teaching videos
Official docs
- Cleanup FAQ
- CAF design area: Platform automation and DevOps
- Elevate access to manage all Azure subscriptions and management groups
Storyboard for the video (about 90 seconds)
This courseware cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: six course cards flip over in turn, and the manual icon on each card turns into a code icon.
Narration: six hours, from manual building to platform as code.
Visual: the corners of the radar chart fill up one by one. The lowest corner flashes and pops up “Revisit Module 4”.
Narration: find the weakest link, then go back and fix it.
Visual: the cleanup checklist is ticked off line by line. Finally, “Elevated access at the root” is crossed out.
Narration: cleanup must follow an order. The last step is always revoking the highest-level access.
Command cheat sheet
Install-PSResource -Name ALZ # or Update-PSResource -Name ALZ Deploy-Accelerator # interactive wizard New-AcceleratorFolderStructure -iacType terraform -versionControl github ` -scenarioNumber 1 -targetFolderPath ~/accelerator Deploy-Accelerator -inputs "~/accelerator/config/inputs.yaml","~/accelerator/config/platform-landing-zone.tfvars" ` -starterAdditionalFiles "~/accelerator/config/lib" -output "~/accelerator/output" Remove-PlatformLandingZone -ManagementGroups "<parent>" -Subscriptions "<s1>","<s2>" -PlanMode Deploy-Accelerator -Destroy
provider "alz" {
library_overwrite_enabled = true
library_references = [{ custom_url = "${path.root}/lib" }]
}
module "alz" {
source = "Azure/avm-ptn-alz/azurerm"
version = "0.23.0"
architecture_name = "alz_custom"
parent_resource_id = "<tenant-id>"
location = "canadacentral"
policy_default_values = { log_analytics_workspace_id = jsonencode({ value = "<id>" }) }
policy_assignments_to_modify = { corp = { policy_assignments = { "Deny-Public-Endpoints" = { enforcement_mode = "DoNotEnforce" } } } }
subscription_placement = { app = { subscription_id = "<id>", management_group_name = "corp" } }
}
# lib/alz_library_metadata.json: dependencies [{ "path": "platform/alz", "ref": "2026.11.0" }]az stack mg create -n NAME --management-group-id MG -l canadacentral \
--template-file main.bicep --parameters main.bicepparam \
--action-on-unmanage detachAll|deleteResources|deleteAll \
--deny-settings-mode none|denyDelete|denyWriteAndDelete \
--deny-settings-excluded-principals "<group-id>" # up to 5
az stack sub show -n NAME --query "resources[].{id:id,s:status,d:denyStatus}" -o table
az stack group delete -n NAME -g RG --action-on-unmanage deleteAllterraform plan -out=tfplan -input=false # artifact terraform apply -input=false tfplan # apply the same file after approval terraform plan -detailed-exitcode # 0 no changes / 1 error / 2 differences gh api repos/ORG/REPO/actions/oidc/customization/sub az identity federated-credential list -g RG --identity-name UAMI -o table
az billing account list
az account alias create --name ALIAS --billing-scope "<scope>" \
--display-name NAME --workload Production|DevTest
az account alias show --name ALIAS --query properties
terraform init -backend-config="key=vending/<name>.tfstate"
# module "lz" { source = "Azure/avm-ptn-alz-sub-vending/azure", version = "0.3.4" }
# Bicep: br/public:avm/ptn/lz/sub-vending:0.8.0Install-PSResource -Name EnterprisePolicyAsCode Build-DeploymentPlans -PacEnvironmentSelector epac-dev Deploy-PolicyPlan -PacEnvironmentSelector epac-dev Deploy-RolesPlan -PacEnvironmentSelector epac-dev Build-DeploymentPlans -PacEnvironmentSelector tenant -BuildExemptionsOnly Export-AzPolicyResources New-ALZPolicyDefaultStructure -DefinitionsRootFolder ./Definitions -Type ALZ -Tag "platform/alz/2026.11.0" Sync-ALZPolicyFromLibrary -DefinitionsRootFolder ./Definitions -Type ALZ -PacEnvironmentSelector epac-dev
git ls-remote --tags https://github.com/Azure/Azure-Landing-Zones-Library.git 'platform/alz/*' git diff --stat platform/alz/2026.10.0 platform/alz/2026.11.0 -- platform/alz terraform init -upgrade az policy set-definition list --management-group alz --query "[?metadata.deprecated]" -o table ./templates/core/governance/tooling/Update-AlzLibraryReferences.ps1 -WhatIf # Bicep
- avm-ptn-alz 0.23.0 · alz 0.22.1 · library platform/alz/2026.11.0 · starter code TF v17.7.0 (still references avm-ptn-alz 0.21.0) / Bicep v2.5.0
- Bootstrap is one-time and does not support upgrades. azurerm supports only 4.x.
- plan UAMI: Reader @ intermediate root; apply UAMI: Owner @ intermediate root; both: Storage Blob Data Contributor on the state container
- Bicep pipeline: deployment stack DenySettingsMode None + ActionOnUnmanage DeleteAll
- The alias API workload is only Production / DevTest. EA allows 5,000 subscriptions per enrollment account.
- EPAC: full deletes resources outside the repo; ownedOnly manages only its own (pacOwnerId)
- caf-enterprise-scale archived 2026-09-15; ALZ-Bicep archived 2027-02-16
Capstone lab + final quiz
Scenario
Northwind Maple (the fictional company from hour 1) has already built its management groups, hub and Log Analytics by hand. The CTO requires: ① every platform change goes through a PR with two people involved; ② new application teams can request a subscription in no more than 1 business day; ③ the governance team can maintain 5 organization audit policies independently, and manual portal policies are removed; ④ the ALZ library is followed monthly; ⑤ an “owner” inventory is delivered.
nwm (change it in the architecture definition in lib). Use your sandbox subscription as the platform subscription. Run only up to the plan. Record the two UAMIs created by Bootstrap and their roles.policy_default_values (workspace ID), and set Deny-Public-Endpoints on corp to DoNotEnforce for two weeks. In the corp_custom override, remove Deploy-Private-DNS-Zones (assuming the local team manages DNS). The PR plan should show exactly these three kinds of changes.terraform plan -detailed-exitcode.requests/ledger-dev.yaml for the application “ledger” (address 10.3.0.0/16, DevTest, corp, budget 150). The PR validates that addresses do not overlap. Plan and apply with the existing-subscription mode, and verify the peering, the UAMI federated credentials, and the budget.epac-dev, deploy 1 organization audit policy (for example, the Audit version of Require a tag on resource groups, or Allowed locations in Audit mode) and 1 exemption that expires in 30 days. Create a shadow assignment by hand, and show that a full-mode plan would delete it.Acceptance checklist
Open-ended self-check (6 questions)
1. Why does the Accelerator use two repositories (main and template) instead of one?
Separate the “execution logic” from the “configuration.” The OIDC subject includes job_workflow_ref, so only the reusable workflow in the template repo can exchange for a token for the plan or apply identity. Even if someone can commit a workflow in the main repo, they cannot get a token. Changes to the template repo need separate approval and carry fewer permissions.
2. The avm-ptn-alz version referenced by the Terraform starter code is behind the latest Registry version. Is that a problem?
It is not an error. The starter code is updated on its own schedule. But it means you must follow module upgrades actively: read the release notes, and use one layer per PR. Do not assume that what Bootstrap gave you is the latest.
3. What does deleteAll in a deployment stack give you, and what risk does it bring?
Benefit: the repo becomes the single source of truth, and removed declarations are really deleted, so nothing is left behind. Risk: a mistaken PR deletes real resources, including ones that hold data. Mitigation: put resources that hold data in a detachAll stack with denyDelete enabled. CI requires extra approval for Delete in the what-if.
4. Why prefer “fix forward” when vending fails?
In new-subscription mode, destroying the vending module cancels the subscription and deletes the network and identity. Most failures (permissions, addresses, policies) can be fixed by correcting the parameters or permissions and rerunning. Resources already created are not duplicated, because they are in state. Rollback applies only when the request itself is rejected and the subscription has not yet been delivered.
5. When EPAC and avm-ptn-alz coexist, what is the most important rule?
Each assignment has one owner. Assignment names must not overlap, and EPAC uses ownedOnly, or excludes ALZ assignments under full. The two EPAC repos use different pacOwnerId values.
6. Why must upgrades be done “one layer per PR”?
Changes to the library, modules, starter code and providers all show up in the plan. When they are mixed together, you cannot trace a replacement to a specific release note, so reviewers can only accept or reject everything as a whole. Splitting by layer makes each PR's changes explainable and reversible.
Sources and versions
Source
| Topic | Source | Page date / version |
|---|---|---|
| IaC Accelerator four phases, Bootstrap, Run, advanced mode, configuration files | Azure Landing Zones docs site (source: Azure/Azure-Landing-Zones) | main branch, accessed 2026-11-18 |
| Cleanup (Remove-PlatformLandingZone, -Destroy), upgrade FAQ (Bootstrap cannot be upgraded, azurerm v5 not supported), permissions FAQ | Same as above: faq/cleanup, faq/upgrade, faq/permissions, starter-terraform/module-index | Accessed 2026-11-18 |
| Objects created by Bootstrap and their default naming, OIDC subject customization, environments and branch protection, stack parameters in the Bicep deployment script | Azure/accelerator-bootstrap-modules (alz/github/variables.tf, modules/github/*.tf, modules/azure/*.tf, alz/local/scripts-bicep/bicep-deploy.ps1) | v7.3.2 (2026-10-10), main branch |
| Terraform starter code structure, version constraints, tfvars examples, archetype overrides | Azure/alz-terraform-accelerator templates/platform_landing_zone | v17.7.0 (2026-11-06) |
| Bicep starter code structure, library metadata, Update-AlzLibraryReferences.ps1 | Azure/alz-bicep-accelerator | v2.5.0 (2026-11-06) |
| avm-ptn-alz inputs, requirements, and the 0.23.0 / 0.22.0 release notes | Terraform Registry; GitHub Releases | 0.23.0 (2026-11-18) |
| alz provider, avm-ptn-alz-management, latest azurerm version | registry.terraform.io (API query) | 0.22.1 (2026-11-03); 0.10.0 (2026-10-27); azurerm 5.14.0 |
| ALZ library version | Azure-Landing-Zones-Library Releases | platform/alz/2026.11.0 (2026-11-06) |
| Deployment stacks | Create and deploy Azure deployment stacks in Bicep | 2026-11-09 |
| Classic ALZ-Bicep migration | Migration from Classic; ALZ-Bicep | Accessed 2026-11-18 |
| caf-enterprise-scale migration | Migration Guidance (aka.ms/alz/tf/migrate) | Accessed 2026-11-18 |
| Subscription vending implementation guide | Subscription vending implementation guidance | 2025-12-15 (updated 2026-10-05) |
| EA subscription programmatic creation, alias API, 5,000 limit | Programmatically create EA subscriptions | 2026-06-07 |
| Vending module (Terraform) | avm-ptn-alz-sub-vending (README v0.3.4); legacy lz-vending | 0.3.4 (2026-10-08); 7.0.3 (2025-11-28) |
| Vending module (Bicep) and permissions | avm/ptn/lz/sub-vending; Sub-vending permissions | 0.8.0 (MCR tag) |
| EPAC | EPAC Docs (index, ci-cd-overview, ci-cd-app-registrations, settings-desired-state, settings-global-setting-file, policy-assignments, policy-exemptions, integrating-with-alz-library) | EnterprisePolicyAsCode 11.5.12 (2026-11-16) |
| ALZ PowerShell module version | PowerShell Gallery: ALZ | 7.1.5 (2026-08-28) |
Video verification note
Every video link on the video tab was checked on 2026-11-18 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) for its title and channel: -X9P8VE94Po, ry39tWr_SXc, DoH5Dc41Fx8, 3FeIFHaJOtg, d1AE8qLwBYw, sPA3YWkQ-4s, FeSMRFkaRIU, aIbtnk2F8Xo, R-5oeguxFpo, x1I_XhC6GtA, Q_Rt-IcXP94, 9JNnHEaQJIs, --I-hPQfLvo, ddcVKS_MKkk, DSBWjQlVpSs, mluS8ovuBKg. Some videos were recorded before this hour's material was written, so version numbers, defaults and retirement dates follow this hour and the official docs.
Voice notes
The “Voice” tab reads the narration script aloud with the browser's Web Speech API (English voice, en-US). No data is uploaded. If no English voice pack is available, you can read the narration script directly.
Known limitations
- All commands were written from the official docs, repo source and CLI help, and have not been run in a real tenant. Outputs (IDs, resource counts, plan summaries, timing) are examples. The Bootstrap plan's resource count varies with VCS and options.
- EPAC command output styling changed in 11.x, so the examples keep only the key information. Subdirectories of plan files follow what you actually get.
- Entries whose error text is marked “follow actual output” (such as some subscription alias and alz provider errors) cannot be verified word for word, so the focus is on diagnostic approach.
- File names, variables and
movedblocks in the Terraform starter code change between versions. Some example paths in the official upgrade guide (such asmodules/management_groups/main.tf) already differ from the actual files in v17.7.0 (main.management.groups.tf). Follow the actual files in your repo. - The animations and simulators are teaching models. The steps and counts for the deployment stack, vending pipeline, EPAC planner and upgrade impact analyzer are simplified illustrations, not the services' internal implementation.
- The billing scope format and required roles for MCA / MPA are only summarized here. Refer to the Cost Management docs. This hour does not actually create subscriptions in an EA environment.