Terraform Hour 3: Moving to the Cloud Platform (Azure)
- Be able to azurerm provider choose the right authentication method (local Azure CLI, service principal, managed identity, GitHub Actions OIDC), and explain why 4.0 requires
subscription_ida subscription ID, and from 5.0 on no longer auto-registers resource providers by default (resource_provider_registrations = "none") are two common pitfalls. - Build with a storage account azurerm remote backend, authenticating with Entra ID (
use_azuread_auth = true) rather than access keys; understand blob lease locks, versioning and soft delete, and least privilegeStorage Blob Data Contributor. - Use
for_eachto generate VNet subnets and NSGs that meet Container Apps subnet delegation and size requirements (minimum for workload profile environments/27). - Deploy two kinds of compute: a Linux VM with cloud-init, and Container Apps that use a user-assigned managed identity + AcrPull to pull images from ACR without passwords.
- Use managed identity + role assignments + Key Vault (RBAC mode) to manage secrets, and use ephemeral resources (Terraform 1.10+) and write-only arguments (1.11+, azurerm's
value_wo) to keep the Redis password out of state. - Know when to use Azure Verified Modules (AVM), and when to use directly azapi (new APIs, preview properties, fields azurerm does not yet support), and recognize AVM module version constraint conflicts with the azurerm version.
- Be able to independently troubleshoot the most common cloud failures: authentication, 403 permission errors, resources that already exist and need import, quotas, unregistered providers, and eventual consistency of role assignments; and before the end of class estimate costs and fully clean up.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (Azure subscription · canadacentral) |
|---|---|---|---|---|---|
| 0 | Pre-class | Warm-up and Azure setup | az CLI login, subscription and permission checks, registering resource providers, preparing the myapp image source, bootstrapping the state storage account | Environment self-check list | bootstrap-state.sh |
| 1 | 00–06 | azurerm provider and authentication | Four authentication methods, credential lookup order,subscription_id, resource provider registration (none by default in 5.0),features block, multi-subscription aliases | "Where do credentials come from" authentication chain simulator | Run the first plan with CLI authentication |
| 2 | 06–13 | azurerm remote backend | Storage account + Entra ID authentication, blob lease locks, versioning/soft delete, state access control,-migrate-state | Two people applying at the same time: lease lock animation | Migrate local state to Azure Blob |
| 3 | 13–21 | Networking: VNet, subnets, NSG | CIDR planning,for_each generating subnets, subnet delegation, NSG rules and associations,cidrsubnet() | count vs for_each subnet deletion comparison | VNet + 3 subnets + NSG |
| 4 | 21–30 | Compute: VMs and Container Apps | VM + cloud-init, ACR, Container Apps environment (VNet integration), user-assigned identity + AcrPull, ingress/probes/scaling | Core animation: Terraform → provider gRPC → ARM REST PUT/polling → write state | ACR + ACA deploy myapp |
| 5 | 30–37 | Identity and secrets | managed identity, role assignments, Key Vault RBAC, ACA secret references, ephemeral/write-only, where sensitive values end up in state | "Will this value end up in state?" comparator | Redis password never lands in state |
| 6 | 37–45 | AVM and azapi | AVM naming and conventions, version constraint conflicts, azapi_resource / azapi_update_resource / data azapi_resource, when to use azapi | azurerm / azapi / AVM selection wizard | Use AVM to build a VNet + azapi to read ACA properties |
| 7 | 45–53 | Troubleshooting on Azure in practice | Authentication failures, 403, already exists → import, quota, MissingSubscriptionRegistration, PrincipalNotFound, ForbiddenByRbac | Role assignment propagation race simulation + Interactive troubleshooting tree | Deliberately cause 4 faults and fix them |
| 8 | 53–60 | Cost, cleanup and self-check | Billing points, tags and budgets,terraform destroy order, soft-delete leftovers, orphaned resource checks | Cost estimator + destroy order animation | destroy + leftover check |
| — | Post-class | Cheat sheet · Capstone lab | One apply delivers the full myapp stack; destroy after verification | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / resources | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| azurerm authentication and subscription selection | ✓ | ✓ | · | · | · | · | ✓ | · | az login,ARM_* environment variables | M1 |
| resource provider registration | ✓ | · | · | ✓ | · | · | ✓ | · | resource_providers_to_register,az provider register | M0 / M7 |
| remote state and locking | · | ✓ | · | · | · | · | ✓ | ✓ | backend "azurerm",force-unlock | M2 |
| networking and for_each | · | · | ✓ | ✓ | · | ✓ | · | · | azurerm_subnet,cidrsubnet() | M3 |
| VM and cloud-init | · | · | ✓ | ✓ | · | · | ✓ | ✓ | azurerm_linux_virtual_machine,custom_data | M4 (optional) |
| Container Apps + ACR passwordless pull | · | · | · | ✓ | ✓ | ✓ | ✓ | · | azurerm_container_app registry.identity | M4 |
| managed identity and role assignments | ✓ | · | · | ✓ | ✓ | · | ✓ | · | azurerm_role_assignment,principal_type | M5 |
| Key Vault and keeping secrets out of state | · | · | · | · | ✓ | · | ✓ | ✓ | ephemeral,value_wo | M5 |
| AVM / azapi selection | · | · | · | · | · | ✓ | ✓ | · | module "avm-res-…",azapi_resource | M6 |
| cloud troubleshooting (import, quota, 403) | ✓ | ✓ | · | ✓ | ✓ | · | ✓ | · | import block,TF_LOG,az vm list-usage | M7 |
| Cost control and full cleanup | · | · | · | ✓ | · | · | · | ✓ | terraform destroy,az keyvault purge | M8 |
What this lesson does not cover (and where to learn it)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
AWS (VPC, ECS Fargate, IAM, S3 backend use_lockfile) | The next lesson covers the same myapp for comparison | Lesson 4: Moving to the Cloud Platform (AWS) |
| Full setup of GitHub Actions pipelines, federated credentials, plan review, Policy | This lesson only covers the OIDC principles and provider configuration in M1 | Lesson 5: Automated operations |
| Multi-environment/multi-region architecture, Landing Zones, Hub-Spoke, full private endpoint coverage | Beyond 1 hour | Lesson 6: Architecture practice;AVM official site |
| AKS clusters and the Kubernetes provider | belongs to the K8s track | Kubernetes 8 + 1-hour lessons |
| Container Apps operational details such as revisions, traffic splitting and KQL logs | The Docker lesson already covered it with az CLI | Docker Hour 3 (Azure) |
| OpenTofu state encryption | Terraform itself does not provide client-side state encryption; it is covered in the advanced topics | Lesson 7 |
How to use this course material
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. Recommended: read "Principles" and "Animation" first, then do the "Lab" in your own subscription.
A quiz score of 70% or higher, or clicking "Mark module complete", counts toward progress; it is saved in this browser (it is cleared on refresh if local storage is blocked).
The "Voice" page reads the lecture script aloud with the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to a TTS tool.
~> 5.14, and it explains the breaking changes of both the 4.0 and 5.0 major versions (subscription_id required, the resource provider registration default changes from legacy to none,skip_provider_registration is removed, and the Key Vault rbac_authorization_enabled becomes required, etc.). Note: many AVM modules still declare azurerm < 5.0 (see module 6), which is one of the most common terraform init causes of failure in the second half of 2026.Module 0 · Warm-up and Azure setup (complete before class)
- CompletedLesson 1andLesson 2: you can write
variable/output/locals/for_each, have usedkreuzwerker/dockerprovider to deploy myapp + Redis locally, and understand state, locks, modules andmoved/importblocks. - Workstation: Ubuntu 24.04 LTS (an Azure VM or a local machine/WSL2), with Docker Engine 29 installed (from the Docker course), Terraform 1.17.x and the latest Azure CLI.
- Azure subscription: your account has Owner, or Contributor + Role Based Access Control Administrator (this lesson creates role assignments, so Contributor alone is not enough).
- Docker course's
~/myapp(Flask + gunicorn + Redis counter, listening on 5000, serving/healthz, configured throughREDIS_HOST/PORT/PASSWORD/SSLto configure Redis).
Connection from the previous lesson
| What you did in lesson 2 | The Azure equivalent in this lesson |
|---|---|
kreuzwerker/docker provider running a container locally | hashicorp/azurerm Calling the Azure Resource Manager (ARM) REST API |
| MinIO simulating S3 for remote state | Azure storage account blob for remote state (native lease locking) |
docker_network + container name access | VNet + subnets + apps reaching each other by name in the Container Apps environment |
sensitive = true variables (values still in state) | ephemeral + write-only: values are not written at all into plan and state |
import blocks adopting existing containers | import blocks adopting resources created manually in the portal (M7) |
Step 1: confirm tool versions and sign in
terraform version
az version --query '"azure-cli"' -o tsv
az login # no-browser environment: az login --use-device-code
az account list -o table
az account set --subscription "<your subscription name or ID>"
az account show --query "{name:name, id:id, tenant:tenantId, user:user.name}" -o table
Terraform v1.17.2 on linux_amd64 2.79.0 Name Id Tenant User -------------- ------------------------------------ ------------------------------------ ---------------- Lab-Subscription 00000000-1111-2222-3333-444444444444 aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee you@contoso.com
The az CLI version number is an example value; see the az version actual output. Terraform below 1.11 cannot use the write-only arguments in M5 of this lesson (value_wo), and below 1.10 cannot use ephemeral resources, so upgrade first.
Step 2: check your role on the subscription
ME=$(az ad signed-in-user show --query id -o tsv) SUB=$(az account show --query id -o tsv) az role assignment list --assignee "$ME" --scope "/subscriptions/$SUB" --include-inherited \ --query "[].roleDefinitionName" -o tsv
Owner
terraform apply will fail at the first azurerm_role_assignment step: AuthorizationFailed … Microsoft.Authorization/roleAssignments/write (M7 reproduces this). In an enterprise subscription, ask your admin for Owner on the lab resource group, or the subscription-level Role Based Access Control Administrator (which can be restricted with a condition to allow only specific roles).Step 3: register the resource providers this lesson needs
From azurerm 5.0 onwards, the default is no longer to register any resource provider (RP) automatically. An RP that is not registered in a new subscription will make apply report MissingSubscriptionRegistration. We register them once before class (this requires subscription-level */register/action permission; Owner and Contributor both have it):
for ns in Microsoft.App Microsoft.ContainerRegistry Microsoft.KeyVault Microsoft.OperationalInsights \
Microsoft.Network Microsoft.Compute Microsoft.Storage Microsoft.ManagedIdentity Microsoft.Cache; do
az provider register --namespace $ns -o none
done
az provider list --query "[?contains('Microsoft.App Microsoft.ContainerRegistry Microsoft.KeyVault Microsoft.OperationalInsights Microsoft.Network Microsoft.Compute Microsoft.Storage Microsoft.ManagedIdentity Microsoft.Cache', namespace)].{ns:namespace, state:registrationState}" -o table
Ns State ------------------------------ ----------- Microsoft.App Registered Microsoft.Cache Registered Microsoft.Compute Registered Microsoft.ContainerRegistry Registered Microsoft.KeyVault Registered Microsoft.ManagedIdentity Registered Microsoft.Network Registered Microsoft.OperationalInsights Registered Microsoft.Storage Registered
You can also let the provider do it: resource_providers_to_register = ["Microsoft.App", …] (covered in M1). Either approach is fine; in enterprise environments the platform team usually registers them centrally, and Terraform uses none.
Step 4: bootstrap the state storage account (the "chicken and egg" problem)
The storage account for a remote backend cannot be created by the same configuration that uses it, since it must already exist at init time. A common approach is a small "bootstrap" configuration or the az CLI to create it first. This lesson uses the az CLI, and disables shared key access from the start, forcing Entra ID:
#!/usr/bin/env bash set -euo pipefail LOC=canadacentral STATE_RG=rg-tfstate STATE_SA=sttfstate$RANDOM # 3–24 lowercase letters/digits, globally unique ME=$(az ad signed-in-user show --query id -o tsv) az group create -n $STATE_RG -l $LOC -o none az storage account create -g $STATE_RG -n $STATE_SA -l $LOC \ --sku Standard_ZRS --kind StorageV2 --min-tls-version TLS1_2 \ --allow-blob-public-access false --allow-shared-key-access false -o none az storage account blob-service-properties update -g $STATE_RG --account-name $STATE_SA \ --enable-versioning true --enable-delete-retention true --delete-retention-days 14 \ --enable-container-delete-retention true --container-delete-retention-days 14 -o none SA_ID=$(az storage account show -g $STATE_RG -n $STATE_SA --query id -o tsv) az role assignment create --assignee-object-id $ME --assignee-principal-type User \ --role "Storage Blob Data Contributor" --scope $SA_ID -o none echo "Waiting for RBAC to take effect (usually 1–5 minutes)..."; sleep 60 az storage container create --account-name $STATE_SA -n tfstate --auth-mode login -o none cat > ~/tf-lab3.env <<EOF export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) export STATE_RG=$STATE_RG export STATE_SA=$STATE_SA EOF echo "Done: $(cat ~/tf-lab3.env)"
mkdir -p ~/tf-lab3 && cd ~/tf-lab3 bash bootstrap-state.sh source ~/tf-lab3.env az storage container list --account-name $STATE_SA --auth-mode login --query "[].name" -o tsv
Waiting for RBAC to take effect (usually 1–5 minutes)... Done: export ARM_SUBSCRIPTION_ID=00000000-1111-2222-3333-444444444444 export STATE_RG=rg-tfstate export STATE_SA=sttfstate21987 tfstate
If az storage container create reports AuthorizationPermissionMismatch, it means role assignments have not finished propagating; wait a minute or two and retry. This is the "eventual consistency" covered in M7. The state storage account is placed in a separate resource group rg-tfstate , so cleaning up the lab resource group after class will not accidentally delete state.
Step 5: confirm the myapp source
ls ~/myapp grep -n "REDIS_\|healthz" ~/myapp/app.py | head
Dockerfile app.py requirements.txt
14: host=os.getenv("REDIS_HOST", "redis"),
15: port=int(os.getenv("REDIS_PORT", "6379")),
16: password=os.getenv("REDIS_PASSWORD") or None,
17: ssl=os.getenv("REDIS_SSL", "false").lower() == "true",
31:@app.route("/healthz")
If not, follow Docker Lesson 3 Module 2 to rebuild app.py (listening on port 5000,/healthz returning ok). The image is built in the cloud in M4 using az acr build in the cloud, so nothing needs to be pushed from this machine.
Warm-up: answer from memory (30 seconds)
During terraform plan, what do Terraform core and the provider each do?
core parses the configuration, builds the dependency graph and reads state, then calls the provider over gRPC for ReadResource (refresh) and PlanResourceChange (compute the diff); the provider talks to the target API (here ARM). During apply, core calls ApplyResourceChange, and writes the new object to state after receiving it. The core animation in M4 expands this chain on Azure.
Does sensitive = true prevent passwords from entering state?
No. sensitive only masks the value in CLI output; the value is still stored in plaintext in state. To keep the value out of state, you need an ephemeral value + write-only argument (M5).
Module 1 · azurerm provider and authentication
- Write a
terraform+providerblock that meets azurerm 5.x requirements: version constraintsfeatures {},subscription_idand resource provider registration policy. - Explain when each of the four authentication methods applies: local Azure CLI, service principal (certificate/secret), managed identity (MSI), and OIDC workload identity federation; know why OIDC is preferred for CI.
- Use
ARM_*environment variables to switch identity and subscription, and configure provider aliases for multiple subscriptions.
required_providers and version constraints; basic concepts of Entra ID app registrations and service principals. Importance:★★★★★ (your first plan failure on Azure is nine times out of ten caused here)What: what the azurerm provider is
hashicorp/azurerm is the official provider jointly maintained by HashiCorp and Microsoft. It translates HCL resources (such as azurerm_container_app) into calls to the Azure Resource Manager (ARM) REST API (https://management.azure.com/subscriptions/…?api-version=…). A few resources also call data plane APIs, such as Key Vault secrets (https://<vault>.vault.azure.net) and storage blobs. Every call requires an OAuth 2.0 access token issued by Microsoft Entra ID: the audience for management plane tokens is https://management.azure.com/, and the audience for Key Vault data plane tokens is https://vault.azure.net.
Why: why authentication configuration deserves its own module
- The same code has to run in three places: your laptop (interactive sign-in), CI pipelines (unattended), and self-hosted runners in Azure (with a managed identity). The code should not hardcode any credentials; instead, the provider should find a suitable identity from the environment.
- Permissions are risk: Terraform identities usually have Contributor or even Owner. A long-lived client secret that leaks is the key to the whole subscription; OIDC and managed identities have no long-term secret to leak.
- Major version changes: 4.0 requires
subscription_idto be given explicitly; 5.0 changes the resource provider registration default tonone, removesskip_provider_registration, and movesenhanced_validationinto thefeaturesblock and disables it by default. Copying configuration from old blogs will cause direct errors.
How: how the provider gets a token
| Method | Switch / environment variable | Token acquisition mechanism | Applicable scenarios |
|---|---|---|---|
| Azure CLI | use_cli (default true) / ARM_USE_CLI | provider calls the local az to get an access token (reusing the az login session), supporting CLI sign-in as a user, service principal and managed identity | Local development, classroom labs |
| Service principal + client secret/certificate | ARM_CLIENT_ID,ARM_TENANT_ID,ARM_CLIENT_SECRET or ARM_CLIENT_CERTIFICATE_PATH | OAuth 2.0 client credentials: POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token | Legacy CI; use a certificate if necessary to avoid secrets |
| Managed identity (MSI) | use_msi = true / ARM_USE_MSI, for a user-assigned identity, grant it ARM_CLIENT_ID | requests a token from the instance metadata service: GET http://169.254.169.254/metadata/identity/oauth2/token (request header Metadata: true) | Self-hosted runners on Azure VM / VMSS, Azure DevOps managed pools |
| OIDC (workload identity federation) | use_oidc = true / ARM_USE_OIDC + ARM_CLIENT_ID,ARM_TENANT_ID | the CI platform issues a short-lived JWT (GitHub Actions via ACTIONS_ID_TOKEN_REQUEST_URL), and the provider uses it as the client_assertion to exchange for an access token with Entra ID; on the Entra side,federated credentials must be configured (issuer + subject must match) | The preferred option for CI: GitHub Actions, Azure DevOps, GitLab, HCP Terraform |
provider docs' recommended wording: use a service principal or managed identity for non-interactive runs (CI), and Azure CLI for local runs. A service principal can be combined with OIDC, in which case there are no long-term secrets at all. Running in AKS also has use_aks_workload_identity.
Provider-level breaking changes for 4.0 and 5.0 (verified)
| Version | Change | What you need to do |
|---|---|---|
| 4.0 (2024-08) | Subscription ID must be provided: in the provider block, or subscription_id or ARM_SUBSCRIPTION_ID (current docs note it can also come from the az CLI default subscription; required for plan/apply,validate is not needed) | Locally export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv); in CI inject as a variable |
| 4.0 | Added resource_provider_registrations (core / extended / all / legacy / none) and resource_providers_to_register; skip_provider_registration Deprecated; in 4.x the default is legacy | choose collections as needed or an explicit list |
| 5.0 (2026-07-28) | resource_provider_registrations Default changed to none: no RP is registered at init; skip_provider_registration is removed | register with az in advance, or resource_providers_to_register = [...]; to keep the old behavior, write "legacy" |
| 5.0 | enhanced_validation move into the features block, with location and RP validation off by default (invalid regions only fail at apply time); adds an optional preflight_enabled (calls ARM Preflight validation at plan time; some resources support it); ARM_PROVIDER_ENHANCED_VALIDATION environment variable is removed | to enable plan-time validation in features.enhanced_validation in the |
When: how to choose
- Locally:
az login+ARM_SUBSCRIPTION_ID, with no credentials written in the provider block. - GitHub Actions / Azure DevOps: OIDC. Create a separate app registration or user-assigned managed identity for each environment (dev/prod), and limit the federated credential subject to the branch or environment.
- Self-hosted runner in Azure: managed identity (no secrets needed; lifecycle follows the VM).
- Client secret: only for legacy platforms that cannot use the above; set a short expiry, store it in a secrets vault, and rotate regularly.
Comparison with other clouds / tools
| azurerm | AWS provider (Lesson 4) | az CLI / Bicep | |
|---|---|---|---|
| Local credentials | Azure CLI session | AWS CLI profile / SSO | Same az login session |
| CI passwordless | OIDC → Entra ID federated credential | OIDC → IAM OIDC provider + AssumeRoleWithWebIdentity | azure/login Action (OIDC) |
| Target scope | subscription (subscription_id), use aliases for multiple subscriptions | account + region (region) | az account set / deployment scope |
| API prerequisite switches | Resource provider registration | None (the service default is available; some require enabling) | Same as azurerm; some CLI commands register automatically |
client_secret = var.x in the provider block makes it secure'. Variable values appear in the plan file, and CI logs may leak them too, so prefer environment variables or OIDC. ② 'Not setting a subscription after az login az login is fine'. When the CLI has multiple subscriptions,ARM_SUBSCRIPTION_ID decides where resources are created, so always set it explicitly to avoid building resources in the production subscription. ③ 'The 5.0 version will register Microsoft.App for me'. It won't; by default none, so the first time a subscription uses Container Apps it will report MissingSubscriptionRegistration. ④ 'OIDC needs a client secret stored in GitHub'. It does not; store only the client ID, tenant ID and subscription ID (they are not secrets).Architecture diagram: four identity sources, one call chain
Flow diagram: GitHub Actions OIDC token exchange
Interactive simulator: where credentials come from
Select a runtime environment, then play through the steps. Each step shows the configuration the provider checks, the real HTTP requests it sends, and how it finally calls ARM. This simulates azurerm's authentication flow; the environment variables and endpoints use real names, and IDs are example values.
Core commands and parameters
| Command / config | Purpose | Key parameters / notes |
|---|---|---|
az login / az account set -s | Establish a CLI session, select a subscription | --use-device-code (no browser); --tenant |
export ARM_SUBSCRIPTION_ID=… | tells the provider the target subscription | Since 4.0, plan/apply must be able to determine the subscription |
az account get-access-token --resource https://management.azure.com/ | Verify the current identity can get an ARM token | For troubleshooting; the output contains expiresOn |
az ad sp create-for-rbac | Create a service principal (demo; prefer OIDC in CI) | --role,--scopes; it outputs a secret, so protect it |
az ad app federated-credential create | Add an OIDC federated credential to an app registration | issuer,subject,audiences |
terraform providers / terraform version | Check the required and installed provider versions | Use with .terraform.lock.hcl |
TF_LOG=DEBUG terraform plan | to inspect authentication details and HTTP requests | Logs include request headers,do not paste them into a public issue |
terraform {
required_version = ">= 1.11" # write-only arguments (M5) require 1.11+
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 5.14" # allows 5.14.x and later 5.x; will not automatically upgrade to 6.0
}
random = {
source = "hashicorp/random"
version = "~> 3.7" # ephemeral random_password available from 3.7
}
time = {
source = "hashicorp/time"
version = "~> 0.13"
}
}
}
provider "azurerm" {
# subscription_id is not hardcoded: it is provided by ARM_SUBSCRIPTION_ID (consistent locally and in CI)
resource_provider_registrations = "none" # 5.0 default; written out for clarity
resource_providers_to_register = [ # only register what this lesson actually uses
"Microsoft.App",
"Microsoft.ContainerRegistry",
"Microsoft.KeyVault",
"Microsoft.OperationalInsights",
]
storage_use_azuread = true # use Entra ID instead of shared keys when accessing the storage data plane
features {
key_vault {
purge_soft_delete_on_destroy = true # lab environment: purge soft delete on destroy so the same name can be recreated
recover_soft_deleted_key_vaults = true
}
resource_group {
prevent_deletion_if_contains_resources = true # refuse deletion if the resource group contains resources Terraform does not know about
}
}
}
How to verify:terraform init after terraform providers shows provider[registry.terraform.io/hashicorp/azurerm] ~> 5.14; if the first plan reports no authentication error, token acquisition succeeded. Common errors: Writing enhanced_validation at the provider top level (from 5.0 it must be inside features); continuing to write skip_provider_registration = true (removed in 5.0; reports Unsupported argument). Production use:resource_providers_to_register Registering providers requires subscription-level permission; pipeline identities with restricted permissions should keep none, and the platform team registers them in advance.
Multiple subscriptions: provider aliases
# shared services subscription's DNS zone + app in the current subscription
provider "azurerm" {
features {}
}
provider "azurerm" {
alias = "shared"
subscription_id = var.shared_subscription_id
features {}
}
data "azurerm_dns_zone" "corp" {
provider = azurerm.shared
name = "corp.example.com"
resource_group_name = "rg-dns"
}
Environment variables quick reference (provider arguments with the same name take precedence)
# local: CLI session + subscription export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) # CI: OIDC (GitHub Actions automatically provides ACTIONS_ID_TOKEN_REQUEST_URL/TOKEN) export ARM_USE_OIDC=true ARM_CLIENT_ID=<app-id> ARM_TENANT_ID=<tenant-id> ARM_SUBSCRIPTION_ID=<sub-id> # Azure VM: user-assigned managed identity export ARM_USE_MSI=true ARM_CLIENT_ID=<uami-client-id> ARM_SUBSCRIPTION_ID=<sub-id> # disable the CLI fallback to avoid CI accidentally using someone else's az session export ARM_USE_CLI=false
Lab 1: run your first plan / apply with Azure CLI authentication (about 5 minutes, cost ≈ 0)
variable "location" {
type = string
default = "canadacentral"
}
variable "prefix" {
type = string
default = "tflab"
}
resource "random_string" "sfx" {
length = 5
upper = false
special = false
}
locals {
suffix = random_string.sfx.result
tags = {
course = "terraform-8h"
lesson = "3-azure"
owner = "you@contoso.com" # change to your email, for cost attribution
expires = "2026-11-16" # reminder to delete
}
}
resource "azurerm_resource_group" "lab" {
name = "rg-tf-lab"
location = var.location
tags = local.tags
}
data "azurerm_client_config" "current" {}
output "whoami" {
value = {
tenant_id = data.azurerm_client_config.current.tenant_id
subscription_id = data.azurerm_client_config.current.subscription_id
object_id = data.azurerm_client_config.current.object_id
}
}cd ~/tf-lab3 && source ~/tf-lab3.env terraform init terraform providers
Initializing provider plugins... - Finding hashicorp/azurerm versions matching "~> 5.14"... - Installing hashicorp/azurerm v5.14.0... - Installed hashicorp/azurerm v5.14.0 (signed by HashiCorp) - Installing hashicorp/random v3.9.1... - Installing hashicorp/time v0.14.2... ... Terraform has been successfully initialized! Providers required by configuration: . ├── provider[registry.terraform.io/hashicorp/azurerm] ~> 5.14 ├── provider[registry.terraform.io/hashicorp/random] ~> 3.7 └── provider[registry.terraform.io/hashicorp/time] ~> 0.13
The patch versions of random/time are examples; use what is actually installed. Commit .terraform.lock.hcl to Git, so the team and CI build with the same provider.
(unset ARM_SUBSCRIPTION_ID; az account clear; terraform plan) 2>&1 | tail -5 az login # sign in again
│ Error: building account: unable to configure ResourceManagerAccount: subscription ID could not be determined and was not specified
az account clear This signs the CLI out; it is only here to reproduce the situation where there is neither an environment variable nor a CLI default subscription. As long as the CLI has a default subscription or ARM_SUBSCRIPTION_ID is set, this error will not appear; but it is still recommended to always set it explicitly, to avoid creating resources in the wrong place when you have multiple subscriptions.
source ~/tf-lab3.env
terraform apply -auto-approve
az group show -n rg-tf-lab --query "{name:name, location:location, tags:tags}" -o jsonc
random_string.sfx: Creating...
random_string.sfx: Creation complete after 0s [id=k3x9q]
azurerm_resource_group.lab: Creating...
azurerm_resource_group.lab: Creation complete after 2s [id=/subscriptions/0000…4444/resourceGroups/rg-tf-lab]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
whoami = {
"object_id" = "9f8e7d6c-…"
"subscription_id" = "00000000-1111-2222-3333-444444444444"
"tenant_id" = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
}TF_LOG=DEBUG terraform plan 2>&1 | grep -E "GET https://management.azure.com" | head -3
… GET https://management.azure.com/subscriptions/0000…4444/resourcegroups/rg-tf-lab?api-version=2020-06-01 …
This is refresh: the provider ReadResource reads the resource group's current state with GET and compares it with state. The api-version is determined by the SDK built into the provider.
Case 1: fully switch to OIDC after a CI secret leak
Problem: A team stored a service principal's ARM_CLIENT_SECRET (valid for 2 years, Owner permission) in GitHub Secrets, and a fork PR workflow printed it into the logs. Approach: rotate the secret immediately; switch to OIDC: one user-assigned managed identity (or app registration) per environment, with the federated credential subject pinned to repo:org/infra:environment:prod; the prod environment requires manual approval; permissions are reduced to resource-group-level Contributor plus a condition-restricted RBAC Administrator. Configuration: the provider block stays the same; only set ARM_USE_OIDC,ARM_CLIENT_ID variables in the workflow. Limitations: the subject must match exactly (branch, tag, environment and PR are different subject formats); requires permissions: id-token: write.
Case 2: after upgrading to azurerm 5.0, applying to a new subscription fails
Problem: The platform upgraded the provider from 4.x to 5.x. Old subscriptions were fine, but a newly created subscription fails at apply with MissingSubscriptionRegistration … Microsoft.App. Cause: 4.x by default legacy automatically registers about 60 RPs at init; in 5.0 the default is none. Old subscriptions were registered long ago, so the problem was never exposed. Approach: register the required RPs in the subscription vending process; Terraform keeps none. Limitations: Registering RPs requires subscription-level permission and should not be given to every application pipeline.
Case 3: resources accidentally created in the production subscription from a laptop
Problem: An engineer's CLI default subscription was prod, but they meant to apply to dev. Approach: each root module fixes the subscription in its terraform.tfvars or backend configuration; add a check block or precondition assertion; data.azurerm_client_config.current.subscription_id == var.expected_subscription_id display the current subscription in the shell prompt. Limitations: assertions only warn at plan time; the real safeguard is not granting write permission on the prod subscription to personal accounts.
Common errors and fixes
Error: building account: unable to configure ResourceManagerAccount: subscription ID could not be determined and was not specified
Cause: Since 4.0 the subscription must be determined: the provider block has no subscription_id, and there is also no ARM_SUBSCRIPTION_ID, the CLI also has no usable default subscription (most common in CI).
env | grep ^ARM_ az account show --query id -o tsv
Fix:export ARM_SUBSCRIPTION_ID=…; in CI inject the subscription ID as a normal variable.
Error: Unsupported argument … An argument named "skip_provider_registration" is not expected here.
Cause: 5.0 has removed this parameter (it was deprecated in 4.x).
Fix: delete it and use resource_provider_registrations = "none" (the 5.0 default). Likewise, the top-level enhanced_validation must be moved to features { enhanced_validation { … } }.
Error: building AzureRM Client: please ensure you have installed Azure CLI version 2.0.79 or newer. Error parsing json result from the Azure CLI: launching Azure CLI: exec: "az": executable file not found in $PATH
Cause: no other authentication method is configured, so the provider falls back to Azure CLI, but the runtime environment (common in CI containers) does not have az installed.
Fix: configure OIDC/MSI environment variables in CI, and set ARM_USE_CLI=false, so the error message points directly at the missing OIDC configuration; locally, install Azure CLI. Error wording varies slightly between versions.
AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:org/infra:ref:refs/heads/feature-x'
Cause: the OIDC token's subject does not match the subject of the federated credential in Entra (for example, the federated credential only configures the main branch or the prod environment).
az ad app federated-credential list --id <app-id> --query "[].{name:name,subject:subject}" -o table
Fix: add federated credentials for the required branches/environments, or make the workflow use a configured environment. Do not loosen this to all branches with wildcards (Entra federated credentials require exact matching; flexible matching needs the dedicated flexible FIC feature, per the official docs).
ManagedIdentityCredential authentication failed / timeout accessing 169.254.169.254
Cause:use_msi = true, but the code is not running on an Azure VM, or the VM does not have the managed identity enabled; a user-assigned identity does not provide ARM_CLIENT_ID.
curl -s -H Metadata:true "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" | head -c 120
Fix: enable the identity on the VM (az vm identity assign), and when there are multiple user-assigned identities, specify the client ID.
1. Write a command that makes Terraform in the current shell use the CLI default subscription, and confirm the provider can get an ARM token.
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) az account get-access-token --resource https://management.azure.com/ --query expiresOn -o tsv terraform plan
2. Write an azurerm 5.x provider block that registers no RPs automatically, registers only Microsoft.App, and validates location at plan time.
provider "azurerm" {
resource_provider_registrations = "none"
resource_providers_to_register = ["Microsoft.App"]
features {
enhanced_validation {
locations = true
}
}
}Company requirement: laptops can plan dev, only the pipeline can apply prod, and no long-lived keys are allowed anywhere. How would you design Terraform authentication?
Locally: az login + ARM_SUBSCRIPTION_ID, the personal account has Contributor on dev but only Reader on prod (plan only). Pipeline: GitHub Actions OIDC; prod uses a separate user-assigned managed identity or app registration, with the federated credential subject limited to environment:prod; the prod environment requires a designated approver; the provider holds no credentials, and CI sets ARM_USE_OIDC=true,ARM_USE_CLI=false. The state storage account is likewise Entra ID only (M2).
Verified instructional videos
Official docs
- azurerm provider documentation (authentication methods and all parameters)
- 5.0 upgrade guide · 4.0 upgrade guide
- Authenticate using OIDC
- Microsoft Entra workload identity federation
Video storyboard (about 90 seconds)
This course material cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.
Scene: a terminal runs terraform plan; an arrow goes from Terraform to a key labeled "Bearer token", then to management.azure.com.
Narration: every azurerm call to Azure Resource Manager first needs an Entra ID access token.
Scene: four sources light up in turn: laptop az login, GitHub OIDC, VM managed identity, service principal secret (grey, with a warning).
Narration: the token can come from Azure CLI, OIDC, managed identity or a service principal. Locally use the CLI, pipelines prefer OIDC, and runners inside Azure use managed identity.
Scene: in the provider block, subscription_id and resource_provider_registrations = "none" are highlighted.
Narration: from version 4.0 the subscription must be determined; from version 5.0 resource providers are no longer registered automatically by default, so you must register them yourself.
Scene: the GitHub workflow YAML contains only a client ID, tenant ID and subscription ID, with no secrets.
Narration: OIDC does not require storing any long-lived secret; this is the best practice for CI authentication.
Module 2 · azurerm remote backend
- Write the recommended
backend "azurerm"configuration:use_azuread_auth = true+ CLI / OIDC / MSI, with no access keys or SAS. - Explain the azurerm backend lock: acquire a lease on the state blob and write the lock information into the blob metadata; read lock conflict information and safely
force-unlock. - Design protection for state: separate resource group + versioning + soft delete + least-privilege RBAC + shared key disabled + resource lock; understand that "can read the state = can read the sensitive values in it".
- Use
terraform init -migrate-stateto migrate the module 1 local state to Azure.
-backend-config partial configuration. Importance:★★★★★What: what the azurerm backend is
backend "azurerm" is a backend built into the Terraform CLI (not a provider, and it does not read the provider block's configuration); it stores state as a block blob in a container of a storage account, with the blob name being key. It natively supports locking and consistency checking (officially: "state locking and consistency checking with Azure Blob Storage native capabilities"), implemented via blob leases.
Why: why remote state is required
- Collaboration: multiple people or pipelines share the same state; locks prevent two applies from overwriting each other.
- Security: state contains resource attributes, often including connection strings, keys and other sensitive values (unless M5's write-only/ephemeral is used). Keeping it on a laptop means secrets scattered everywhere.
- Recoverability: blob versioning lets you roll back to the previous state; soft delete protects against accidental deletion.
How: authentication methods and required permissions (verified against the Terraform v1.17 docs)
| Method | backend parameter | Required permission | Recommendation |
|---|---|---|---|
| Entra ID + Azure CLI | use_cli = true,use_azuread_auth = true | container on Storage Blob Data Contributor | local ✓ |
| Entra ID + OIDC | use_oidc = true,use_azuread_auth = true,client_id,tenant_id | same as above | CI ✓✓ |
| Entra ID + managed identity | use_msi = true,use_azuread_auth = true (user-assigned, then give client_id) | same as above | Azure self-hosted runner ✓✓ |
| access key lookup | given resource_group_name and not set use_azuread_auth | Reader + Storage Account Key Operator Service Role | ✗ legacy |
| access key / SAS | access_key / sas_token (or ARM_ACCESS_KEY) | no RBAC needed, possession of the key is enough | ✗ backward compatibility only |
only needed when setting lookup_blob_endpoint = true (Azure DNS zone endpoint) requires the management plane Reader and resource_group_name/subscription_id. The official docs warn: values passed through -backend-config or hardcoded in configuration are saved in the .terraform directory and in plan files, so credentials should go through environment variables.
Real lock mechanics
- When plan/apply starts, the backend sends
PUT …/tfstate/<key>?comp=leaseto the state blob, with request headerx-ms-lease-action: acquire, to get an indefinite lease, obtainingx-ms-lease-id; if the blob does not exist, it first creates an empty blob. - Writes the lock information (ID, operation, who, version, time) as JSON into the blob's metadata (
terraformlockid). - Other processes requesting a lease again get
409 LeaseAlreadyPresent, and the backend reads the metadata and prints "Error acquiring the state lock" and Lock Info. - When writing state, it overwrites the blob with the lease ID; after finishing,
x-ms-lease-action: releasereleases it. If the process is force-killed, the lease does not expire automatically (it is indefinite), so you needterraform force-unlock <ID>(underneath it is break lease).
workspace and key
The default workspace uses key itself; other workspaces' blob names are <key>env:<workspace> (for example lab3/myapp.tfstateenv:dev). In production it is more common to use one key per environment (or even one container/storage account)
, so RBAC can separate permissions.
- When: how to organize Place the state storage account in a separate resource group and subscription
CanNotDelete(platform/management subscription), and add a - resource lock; do not tie it to application resources.
<system>/<environment>/<component>.tfstate. Use a separate container for prod, and grant only the prod pipeline identity Data Contributor. - Enable blob versioning + soft delete (14 days in this lesson); disable shared key access (
allowSharedKeyAccess=false), so all access can be audited in Entra logs. - When network isolation is needed, use private endpoints, and make sure the CI runner can resolve and reach them (Microsoft-hosted GitHub runners cannot reach private endpoints).
Comparison with other backends
| azurerm (this lesson) | s3 (lessons 2 and 4) | HCP Terraform | |
|---|---|---|---|
| Locking | blob lease (native) | use_lockfile = true S3 native conditional writes (DynamoDB locking is deprecated) | Platform-managed |
| Authentication | Entra ID (CLI/OIDC/MSI) | IAM (profile/OIDC role) | platform token; dynamic credentials to access the cloud |
| History | blob versioning | S3 versioning | built-in state version history |
| Encryption at rest | storage server-side encryption (Microsoft-managed keys by default; CMK optional) | SSE-S3 / SSE-KMS | Platform encryption |
-lock=false, which only suits PR previews. ③ 'Variables can be used inside the backend block': no; the backend is initialized before variable evaluation, so use -backend-config a file or environment variables for partial configuration. ④ 'force-unlock is safe': only run it after confirming the lock-holding process has ended; otherwise two processes may write state at the same time.Architecture diagram: the state storage security boundary
Sequence diagram: backend and Blob service interaction during one apply
Animation: Alice and Bob apply at the same time
Play the process of two people running terraform apply almost simultaneously. Watch the blob's lease status, the error Bob receives, and how the stale lock is handled after Alice's process is force-killed with Ctrl+C.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
terraform init -migrate-state | copy existing state to the new backend when the backend changes | prompts for confirmation; -force-copy skip confirmation (CI) |
terraform init -reconfigure | re-initialize, ignoring the old backend configuration (no migration) | use when switching to a backend that already has state |
terraform init -backend-config=FILE | partial configuration: put environment-specific values in a file | can be used multiple times; or also -backend-config="key=value" |
terraform force-unlock LOCK_ID | release a stale lock | first confirm the lock-holding process has ended; -force skip confirmation |
terraform state pull > backup.tfstate | download the current state (backup / troubleshooting) | the output contains sensitive values; be careful where it is saved |
az storage blob list --include v --auth-mode login | list the state's version history | --prefix lab3/ |
az storage blob show … --query properties.lease | view lease status | status/state/duration |
az lock create --lock-type CanNotDelete | add a delete lock to the state storage account | --resource-group,--resource,--resource-type |
terraform {
backend "azurerm" {
use_azuread_auth = true # access the blob with Entra ID, not access keys
use_cli = true # local; in CI change to environment variable ARM_USE_OIDC=true
container_name = "tfstate"
key = "lab3/myapp.tfstate"
# storage_account_name is provided via -backend-config (each person's name is different)
}
}
# partial configuration: put the account name in a file (not a secret, can be committed; secrets must go through environment variables) cat > backend.hcl <<EOF storage_account_name = "$STATE_SA" EOF terraform init -migrate-state -backend-config=backend.hcl
Initializing the backend... Do you want to copy existing state to the new backend? Pre-existing state was found while migrating the previous "local" backend to the newly configured "azurerm" backend. No existing state was found in the newly configured "azurerm" backend. Do you want to copy this state to the new "azurerm" backend? Enter "yes" to copy and "no" to start with an empty state. Enter a value: yes Successfully configured the backend "azurerm"! Terraform will automatically use this backend unless the backend configuration changes.
How to verify:az storage blob list --account-name $STATE_SA -c tfstate --auth-mode login -o table can see lab3/myapp.tfstate; locally terraform.tfstate becomes an empty file (can be deleted after confirmation; there is also terraform.tfstate.backup). Common errors: forgetting use_azuread_auth makes the backend try to use access keys, but shared key access is disabled → 403. Production use: in CI use terraform init -input=false -backend-config=prod.backend.hcl, together with ARM_USE_OIDC.
The OIDC version in CI
# environment variables in a GitHub Actions job (shared by backend and provider) export ARM_USE_OIDC=true ARM_USE_AZUREAD=true ARM_USE_CLI=false export ARM_CLIENT_ID=<app-id> ARM_TENANT_ID=<tenant-id> ARM_SUBSCRIPTION_ID=<sub-id> terraform init -input=false -backend-config=prod.backend.hcl
ARM_USE_AZUREAD corresponds to the backend's use_azuread_auth; or write it directly in the backend block, use_azuread_auth = true, in which case CI only needs to provide identity-related variables.
Lab 2: migrate local state to Azure Blob, and practice locks and rollback (about 6 minutes, cost ≈ 0.01 USD)
cd ~/tf-lab3 && source ~/tf-lab3.env
terraform init -migrate-state -backend-config=backend.hcl
terraform state list
az storage blob list --account-name $STATE_SA -c tfstate --auth-mode login --query "[].{name:name, size:properties.contentLength}" -o table
azurerm_resource_group.lab data.azurerm_client_config.current random_string.sfx Name Size ------------------ ------ lab3/myapp.tfstate 2875
# Terminal A: do not type yes; leave it at the confirmation prompt (the lock is now held) terraform apply # Terminal B: cd ~/tf-lab3 && source ~/tf-lab3.env && terraform plan -lock-timeout=10s az storage blob show --account-name $STATE_SA -c tfstate -n lab3/myapp.tfstate --auth-mode login --query properties.lease -o jsonc
│ Error: Error acquiring the state lock
│
│ Error message: state blob is already locked
│ Lock Info:
│ ID: 5b0c7a2e-6f1d-2b8e-91aa-0c4d7e2f9a11
│ Path: tfstate/lab3/myapp.tfstate
│ Operation: OperationTypeApply
│ Who: you@lab-vm
│ Version: 1.17.2
│ Created: 2026-11-15 10:21:07.123456 +0000 UTC
│ Info:
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.
{
"duration": "infinite",
"state": "leased",
"status": "locked"
}
Back in terminal A, type no to cancel; the lock is released normally (status changes back to unlocked). The exact wording of the error message may vary slightly across Terraform versions.
# Terminal A: run terraform apply again, leaving it at the confirmation prompt, then force-kill it from another terminal pkill -9 -f "terraform apply" terraform plan -lock-timeout=5s 2>&1 | grep -E "ID:|Who:" terraform force-unlock <ID shown above>
│ ID: 8d1e… │ Who: you@lab-vm Do you really want to force-unlock? Terraform will remove the lock on the remote state. This will allow local Terraform commands to modify this state, even though it may still be in use. Only 'yes' will be accepted to confirm. Enter a value: yes Terraform state has been successfully unlocked!
az storage blob list --account-name $STATE_SA -c tfstate --auth-mode login --include v \
--prefix lab3/ --query "[].{ver:versionId, current:isCurrentVersion, modified:properties.lastModified}" -o table
# restore (example): copy a historical version back as the current version
# az storage blob copy start --account-name $STATE_SA --destination-container tfstate \
# --destination-blob lab3/myapp.tfstate --auth-mode login \
# --source-uri "https://$STATE_SA.blob.core.windows.net/tfstate/lab3/myapp.tfstate?versionId=<VERSION_ID>"
Ver Current Modified ---------------------------- --------- ------------------------- 2026-11-15T10:18:42.1234567Z 2026-11-15T10:18:42+00:00 2026-11-15T10:24:10.7654321Z True 2026-11-15T10:24:10+00:00
Restoring an old state version is a high-risk operation (state will "forget" resources created after that version), so only do it when state is corrupted, and first terraform state pull back up the current version.
az lock create -n lock-tfstate --lock-type CanNotDelete -g $STATE_RG \ --resource $STATE_SA --resource-type Microsoft.Storage/storageAccounts -o table
Before cleaning up at the end of the course, rg-tfstate you need to first az lock delete -n lock-tfstate -g $STATE_RG --resource $STATE_SA --resource-type Microsoft.Storage/storageAccounts (see M8).
Case 1: move from access keys to Entra ID
Problem: For years the pipelines used ARM_ACCESS_KEY to access state; the key was copied across multiple Variable Groups, and there was no way to audit who read the state. Approach:① give all pipeline identities (OIDC) Storage Blob Data Contributor at container level; ② add use_azuread_auth = true to the backend block and delete ARM_ACCESS_KEY; ③ after a week with no 403 errors, set allowSharedKeyAccess=false and rotate both keys. Limitations: some older tools (such as old versions of Storage Explorer scripts) rely on keys and must be updated at the same time.
Case 2: state storage account accidentally deleted
Problem: Someone cleaned up a resource group that looked unused and deleted the state storage account along with it. Approach: Azure supports recovering a deleted storage account within a certain period (the portal's "Restore deleted account", per the official docs); afterwards, move the state account to the management subscription, add a CanNotDelete resource lock, an Azure Policy that denies deletion, and enable container soft delete. Limitations: a resource lock blocks everyone (including Terraform's own destroy when it manages that account), which is exactly why bootstrap uses a separate configuration.
Case 3: isolate state permissions by environment
Problem: Developers could read prod state, which contains database administrator passwords. Approach: prod uses a separate container tfstate-prod, granting Data Contributor only to the prod deployment identity; developers only have dev container permissions; and the password is changed to write-only (M5), so no secret appears in state. Limitations: container-level RBAC needs to be scoped to the container resource ID (…/blobServices/default/containers/tfstate-prod).
Common errors and fixes
Error: Failed to get existing workspaces: … Status=403 Code="AuthorizationPermissionMismatch" Message="This request is not authorized to perform this operation using this permission."
Cause: Entra ID authentication succeeded, but the identity has no data plane role on the container (Contributor/Owner are management plane roles,do not include read/write blob data permission), or the role assignment was just created and has not propagated yet.
SA_ID=$(az storage account show -g $STATE_RG -n $STATE_SA --query id -o tsv)
az role assignment list --scope $SA_ID --include-inherited --query "[].{who:principalName, role:roleDefinitionName}" -o table
Fix: assign Storage Blob Data Contributor (at container or account level), then wait a few minutes and retry.
Status=403 Code="KeyBasedAuthenticationNotPermitted" Message="Key based authentication is not permitted on this storage account."
Cause: the storage account has shared keys disabled, but the backend still uses access keys (not setting use_azuread_auth = true, given resource_group_name so it looks up keys, or setting ARM_ACCESS_KEY).
Fix: add use_azuread_auth = true to the backend, remove access_key/ARM_ACCESS_KEY, then terraform init -reconfigure.
Error acquiring the state lock … state blob is already locked
Cause: another process is running, or a previous process was force-killed and left its lease behind.
az storage blob show --account-name $STATE_SA -c tfstate -n lab3/myapp.tfstate --auth-mode login --query "{lease:properties.lease, meta:metadata}" -o jsonc
Fix: first confirm that the process or pipeline in Who has ended (check the CI run history), then terraform force-unlock <ID>. In CI you can set -lock-timeout=5m so queued jobs wait instead of failing immediately.
Error: Backend configuration changed … A change in the backend configuration has been detected, which may require migrating existing state.
Cause: the backend block or -backend-config value was changed.
Fix: to carry the state over: terraform init -migrate-state; if you are only switching to another existing state: terraform init -reconfigure.
Error: Variables not allowed … on backend.tf line 5, in terraform: storage_account_name = var.state_sa
Cause: the backend block is initialized before variable evaluation, so variables and expressions are not supported.
Fix: use -backend-config a file or command-line arguments (partial configuration).
1. Change the backend's key to lab3/prod.tfstate and copy the existing state over (non-interactive, suitable for CI).
terraform init -migrate-state -force-copy -input=false \ -backend-config=backend.hcl -backend-config="key=lab3/prod.tfstate"
2. View the current lease status and the number of historical versions of the state blob.
az storage blob show --account-name $STATE_SA -c tfstate -n lab3/myapp.tfstate --auth-mode login --query properties.lease az storage blob list --account-name $STATE_SA -c tfstate --auth-mode login --include v --prefix lab3/myapp.tfstate --query "length(@)"
The security team requires that no one can access state with keys, all access is auditable, and only the prod pipeline can write prod state, while developers must be able to see the prod plan preview in PRs. How would you design it?
state account allowSharedKeyAccess=false, with a unified backend use_azuread_auth = true; prod uses a separate container, and the prod deployment identity (OIDC, subject limited to environment:prod) has Storage Blob Data Contributor on that container; PR previews use another read-only identity (Storage Blob Data Reader + subscription Reader) that runs terraform plan -lock=false (read-only cannot acquire the lease). Note that the preview identity can read values in state, so also change the secrets to write-only or Key Vault references. Enable storage diagnostic logs and Entra sign-in logs to meet audit requirements.
Verified instructional videos
Official docs
- Backend Type: azurerm (Terraform v1.17)
- Microsoft Learn: storing Terraform state in Azure Storage
- Blob REST API: Lease Blob
- Forbid shared key authorization
Video storyboard (about 80 seconds)
This course material cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.
Scene: the terraform.tfstate file on a laptop is zoomed in, with a line containing password highlighted.
Narration: state contains all of a resource's attributes, often including secrets. It should not sit on a laptop.
Scene: storage account, container and blob, with a lock icon labeled lease acquire beside them.
Narration: the azurerm backend stores state as one blob; it acquires a lease when an operation starts, so anyone else who comes along gets a conflict and sees the lock information.
Scene: the key icon is crossed out and replaced with an Entra ID badge and "Storage Blob Data Contributor".
Narration: use Entra ID authentication, disable shared keys, and every access has an identity and can be audited.
Scene: multiple state versions on a timeline; clicking one restores it.
Narration: turn on versioning and soft delete, so if state goes wrong you can go back to the previous version.
Module 3 · Networking: VNets, subnets, NSGs
- Use
cidrsubnet()to derive each subnet address from a /16, avoiding manual math and overlaps. - Use
for_each+ map to generate subnets (with delegation) and NSG rules, and understand whycountremoving a middle element triggers a chain of replacements. - Meets the Azure Container Apps (workload profile environment) subnet requirements: delegated to
Microsoft.App/environments, at least/27, and cannot be resized after creation. - Associate an NSG with the VM subnet, allowing SSH only from your IP.
for_each,dynamic blocks; Azure VNet basics. Importance:★★★★☆What: this lesson's network topology
One VNet vnet-tflab (10.30.0.0/16, canadacentral), three subnets:
| Subnet | CIDR | Purpose | Special requirements |
|---|---|---|---|
snet-aca | 10.30.0.0/23 = cidrsubnet("10.30.0.0/16", 7, 0) | Container Apps environment (workload profile) | Delegated to Microsoft.App/environments; used only by ACA |
snet-vm | 10.30.2.0/24 = cidrsubnet(…, 8, 2) | Linux VM (optional in M4) | Attach NSG: SSH allowed only from your public IP |
snet-pe | 10.30.3.0/24 = cidrsubnet(…, 8, 3) | Reserved for private endpoints (Lesson 6) | Attach NSG (default rule denies inbound from the Internet) |
Why: why plan networking first
- Cannot be changed: the subnet size of an ACA environment cannot be changed after creation; once a VNet's address space overlaps with peered or on-premises networks, migration is hard.
- Platform reservations: each Azure subnet reserves 5 addresses; an ACA workload profile environment also permanently uses 12 addresses for infrastructure, and switching revisions in single-revision mode briefly needs double the addresses. Official table: /27 has 18 usable addresses, with up to about 90 replicas on the Consumption profile; /23 has 498 usable addresses.
- Reserved ranges: the ACA subnet must not overlap with
169.254.0.0/16,172.30.0.0/16,172.31.0.0/16,192.0.2.0/24ranges, and workload profile environments also reserve100.100.0.0/17and several other ranges. This lesson chooses10.30.0.0/16to avoid these.
How: generate subnets with for_each
Write the subnets as a map (keys are stable logical names),for_each creating one azurerm_subnet, with resource address azurerm_subnet.this["aca"]. Adding or removing one subnet only affects that one key, whereas count count addresses by index, so deleting a middle item shifts all later ones and Terraform plans to modify (or even replace) them. For subnets, this can mean deleting a subnet that is still in use.
Delegation: hand a subnet over to an Azure service to manage (the service injects network interfaces/policies into the subnet). An ACA workload profile environment requires delegation to Microsoft.App/environments; A Consumption-only environment is the opposite: it requires no delegation and at least /23. This lesson uses the workload profile environment (the officially recommended default type).
NSG: stateful 5-tuple filtering; rules are matched by priority (100–4096, lower number wins). Default rules allow traffic within the VNet and Azure Load Balancer probes, and deny all other inbound. An NSG is attached via azurerm_subnet_network_security_group_association to a subnet (or to a NIC).
Two ways to write subnets (do not mix them)
Standalone azurerm_subnet resource (this lesson) | azurerm_virtual_network Inline subnet block | |
|---|---|---|
| Pros | Can be referenced individually, associated with NSGs/route tables, and works naturally with for_each | One PUT creates the VNet and subnets; since 4.0, inline blocks support more options such as delegation and route tables |
| Risks | None | Mixing with standalone azurerm_subnet resources causes them to overwrite each other (one sees an extra subnet, the other deletes it) |
5.0 change: azurerm_subnet The VNet inline subnet service_endpoints list was removed in favor of service_endpoint blocks (check the 5.x docs for fields).
When: when to use a custom VNet
- When you need to reach databases/Key Vault behind private endpoints, need a fixed egress IP (NAT Gateway), need an internal environment (no public ingress), or need external TCP ingress (official docs: external TCP ingress is only supported in environments that use a VNet).
- For a public HTTP demo only, ACA can also run without a VNet (the platform generates one). This lesson uses a custom VNet to stay close to production and to demonstrate for_each.
Comparison with AWS / Docker
| Azure | AWS (Lesson 4) | Docker (Lesson 2, local machine) |
|---|---|---|
| VNet (regional, subnets span availability zones) | VPC (subnets bound to a single AZ) | bridge network |
| NSG (subnet/NIC, stateful) | Security Group (ENI, stateful) + NACL (subnet, stateless) | iptables rules |
| Subnet delegation | No direct equivalent (the service brings its own ENI) | — |
Topology diagram: vnet-tflab
Data flow: how one map becomes multiple resources
Interactive comparison: count vs for_each when deleting a middle subnet
There are 4 subnets by default: a, b, c, d. Click a subnet to remove it from the list, and observe the results under both approaches terraform plan results. The "~ update / -/+ replace" in the animation corresponds to the real symbols in the plan; on Azure, modifying a subnet's address_prefixes is rejected (when resources are in the subnet) or triggers replacement.
Core commands and parameters
| Command / function | Purpose | Notes |
|---|---|---|
cidrsubnet(prefix, newbits, netnum) | Derive subnets from a prefix | cidrsubnet("10.30.0.0/16", 8, 2) → 10.30.2.0/24 |
terraform console | Validate expressions interactively | Validate the CIDR before writing resources |
terraform plan -target=azurerm_subnet.this[\"aca\"] | Inspect one subnet (for troubleshooting) | Do not use -target as a routine workflow |
az network vnet subnet list | Verify actual subnets and delegation | --query "[].{n:name,p:addressPrefix,d:delegations[0].serviceName}" |
az network nsg rule list | List NSG rules (including default rules) | --include-default |
az network watcher test-ip-flow | Check whether a 5-tuple is allowed by the NSG | Requires the VM NIC; for troubleshooting connection failures |
terraform console
> cidrsubnet("10.30.0.0/16", 7, 0)
"10.30.0.0/23"
> [for n in [2,3] : cidrsubnet("10.30.0.0/16", 8, n)]
[
"10.30.2.0/24",
"10.30.3.0/24",
]
> exit
variable "admin_cidr" {
description = "Source allowed to reach the VM over SSH/HTTP (your public IP/32)"
type = string
}
locals {
vnet_cidr = "10.30.0.0/16"
subnets = {
aca = { newbits = 7, netnum = 0, delegation = "Microsoft.App/environments", nsg = false }
vm = { newbits = 8, netnum = 2, delegation = null, nsg = true }
pe = { newbits = 8, netnum = 3, delegation = null, nsg = true }
}
nsg_rules = {
vm = {
ssh = { priority = 110, port = "22" }
http = { priority = 120, port = "80" }
}
pe = {}
}
}
resource "azurerm_virtual_network" "lab" {
name = "vnet-${var.prefix}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
address_space = [local.vnet_cidr]
tags = local.tags
}
resource "azurerm_subnet" "this" {
for_each = local.subnets
name = "snet-${each.key}"
resource_group_name = azurerm_resource_group.lab.name
virtual_network_name = azurerm_virtual_network.lab.name
address_prefixes = [cidrsubnet(local.vnet_cidr, each.value.newbits, each.value.netnum)]
dynamic "delegation" {
for_each = each.value.delegation == null ? [] : [each.value.delegation]
content {
name = "delegation-${each.key}"
service_delegation {
name = delegation.value
actions = ["Microsoft.Network/virtualNetworks/subnets/join/action"]
}
}
}
}
resource "azurerm_network_security_group" "this" {
for_each = { for k, v in local.subnets : k => v if v.nsg }
name = "nsg-${each.key}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
tags = local.tags
dynamic "security_rule" {
for_each = local.nsg_rules[each.key]
content {
name = "allow-${security_rule.key}"
priority = security_rule.value.priority
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = security_rule.value.port
source_address_prefix = var.admin_cidr
destination_address_prefix = "*"
}
}
}
resource "azurerm_subnet_network_security_group_association" "this" {
for_each = azurerm_network_security_group.this
subnet_id = azurerm_subnet.this[each.key].id
network_security_group_id = each.value.id
}
output "subnet_ids" {
value = { for k, s in azurerm_subnet.this : k => s.id }
}
How to verify: The plan shows azurerm_subnet.this["aca"] and similar keyed addresses; after apply, az network vnet subnet list shows the delegation of the aca subnet. Common error:for_each map keys that depend on values only known after apply (such as resource IDs) produce Invalid for_each argument— keys must be known at plan time. Production use: Replace local.subnets with a variable, and you have a reusable network module; in production, using AVM's VNet module directly is recommended (M6).
Lab 3: VNet + 3 subnets + NSG (about 5 minutes; the VNet and NSG themselves are free)
cd ~/tf-lab3 MYIP=$(curl -s https://api.ipify.org) echo "admin_cidr = \"$MYIP/32\"" > terraform.tfvars cat terraform.tfvars
admin_cidr = "203.0.113.25/32"
terraform plan -out=net.tfplan | grep -E "^ # |address_prefixes|will be created" | head -20
# azurerm_network_security_group.this["pe"] will be created
# azurerm_network_security_group.this["vm"] will be created
# azurerm_subnet.this["aca"] will be created
+ address_prefixes = [
# azurerm_subnet.this["pe"] will be created
# azurerm_subnet.this["vm"] will be created
# azurerm_subnet_network_security_group_association.this["pe"] will be created
# azurerm_subnet_network_security_group_association.this["vm"] will be created
# azurerm_virtual_network.lab will be createdterraform apply net.tfplan
az network vnet subnet list -g rg-tf-lab --vnet-name vnet-tflab \
--query "[].{name:name, prefix:addressPrefix, delegation:delegations[0].serviceName, nsg:networkSecurityGroup.id}" -o table
Name Prefix Delegation Nsg -------- ------------- -------------------------- ------------------------------ snet-aca 10.30.0.0/23 Microsoft.App/environments snet-pe 10.30.3.0/24 /subscriptions/…/nsg-pe snet-vm 10.30.2.0/24 /subscriptions/…/nsg-vm
local.subnets a temporary subnet to tmp = { newbits = 8, netnum = 9, delegation = null, nsg = false }, run plan → only adds ["tmp"]; remove it and run plan again → only destroys ["tmp"], and other subnets are unaffected.
terraform plan | grep -E "Plan:|\[\"tmp\"\]"
# azurerm_subnet.this["tmp"] will be created Plan: 1 to add, 0 to change, 0 to destroy.
Case 1: ACA subnet too small causes release failure
Problem: The team used /27 for ACA; 40 replicas were fine normally. During a big promotion, max_replicas was raised to 120, and publishing a new revision reported insufficient addresses. Cause:/27 has only 18 usable addresses, and switching in single-revision mode doubles the address requirement. Fix: Create a /23 subnet and a new environment, and migrate the app blue-green (an environment's subnet cannot be modified). Limitation: Both environments run during migration; plan for costs and the DNS cutover.
Case 2: subnet created by count was deleted by mistake
Problem: Legacy code count = length(var.subnet_cidrs), someone deleted an unused subnet from the middle of the list; the plan showed the two subsequent subnets needing "modify address_prefixes", and during apply Azure reported InUseSubnetCannotBeUpdated, leaving half the resources in an inconsistent state. Fix: Switch to for_each and use moved blocks to move azurerm_subnet.this[0] to azurerm_subnet.this["app"], avoiding recreation. Configuration:moved { from = azurerm_subnet.this[0] to = azurerm_subnet.this["app"] }. Limitation: Each element needs its own moved block (or generate them with a script).
Case 3: NSG rule drift
Problem: An on-call engineer temporarily added an "allow 3389 from any source" rule in the portal and forgot to remove it. Fix: NSG rules are fully managed by Terraform (inline security_rule removes portal-added rules on the next apply); run on a schedule terraform plan -detailed-exitcode to detect drift and alert; also add Azure Policy to deny management ports from the Internet. Limitation: Inline rules and standalone azurerm_network_security_rule resources cannot be mixed.
Common errors and fixes
NetcfgInvalidSubnet / Subnet 'snet-x' is not valid in virtual network 'vnet-tflab' … overlaps with
Cause: Subnet CIDRs overlap or fall outside the VNet address space (common when CIDRs are calculated by hand).
terraform console <<< 'cidrsubnet("10.30.0.0/16", 7, 1)'
Fix: Use cidrsubnet() to derive them consistently; note that a /23 occupies the space of two /24s (netnum count each by its own newbits).
InUseSubnetCannotBeDeleted: Subnet snet-aca is in use by …/managedEnvironments/… and cannot be deleted
Cause: The subnet is still in use by an ACA environment (or another service's NIC/service association link), and Terraform's dependency graph may be missing the relationship (for example, the environment is managed by another root module).
Fix: Delete the consumer (the environment) before the subnet; across root modules, adjust the destroy order. After an ACA environment is deleted, the service association link takes a few minutes to release; retry during that time.
ManagedEnvironmentSubnetIsDelegated / The subnet … must be delegated to Microsoft.App/environments (or the reverse: must not be delegated)
Cause: The environment type does not match the subnet delegation: workload profile environments require delegation, and Consumption-only environments require no delegation. Use the actual returned error code name.
Fix: workload profile environment (this lesson): add the subnet Microsoft.App/environments delegation with ≥ /27; Consumption-only: remove delegation and use ≥ /23.
Error: Invalid for_each argument … The "for_each" map includes keys derived from resource attributes that cannot be determined until apply
Cause: map keys used a value only known after apply (such as azurerm_subnet.x.id).
Fix: Use static logical names for keys (aca/vm/pe), and put unknown values inside the map's values.
SecurityRuleConflict / SecurityRuleParameterContainsUnsupportedValue … priority
Cause: Two rules in the same direction have the same priority, or the priority is outside 100–4096.
Fix: Assign a unique priority to each rule, increasing in steps of 10 to leave room for insertions.
1. Use one expression to compute 10.30.0.0/16 the 4th, 5th, and 6th /24 (netnum 4–6).
[for n in range(4, 7) : cidrsubnet("10.30.0.0/16", 8, n)]
# → ["10.30.4.0/24", "10.30.5.0/24", "10.30.6.0/24"]2. List the delegated service and address prefix of snet-aca.
az network vnet subnet show -g rg-tf-lab --vnet-name vnet-tflab -n snet-aca \
--query "{prefix:addressPrefix, delegation:delegations[0].serviceName}" -o tableThe existing code uses count to create 3 subnets (indexes 0, 1, 2). You need to delete the middle one without affecting the other two. Provide a zero-downtime migration plan.
① Change the variable to a map (keys app/data/mgmt) and change the resource to for_each; ② add moved { from = azurerm_subnet.this[0] to = azurerm_subnet.this["app"] } three moved blocks; ③ run plan and confirm it only shows "has moved to" with no creates or destroys, then apply; ④ remove the middle key from the map, run plan so it shows only the destruction of that one subnet (confirm no resource is using it), then apply; ⑤ afterward you can remove the moved blocks (it is advisable to keep them for a while so other workspaces can sync).
Verified teaching videos
Official documentation
- azurerm_subnet · azurerm_network_security_group
- Container Apps custom virtual networks (subnet size, delegation, reserved ranges)
- cidrsubnet function · for_each
Video storyboard (about 75 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided for a video tool to generate.
Visual: a /16 block is split into a /23 and two /24s, labeled with cidrsubnet parameters.
Narration: Plan the addresses first. Use cidrsubnet to derive subnets from one large range, avoiding manual overlaps.
Visual: on the left, a count list has a middle element deleted and the following elements turn red; on the right, for_each has only one element disappear.
Narration: count addresses by index, so deleting a middle item changes all the ones after it; for_each addresses by key, so items don't affect each other.
Visual: on snet-aca, a "delegated to Microsoft.App/environments" label and a "≥ /27" hint appear.
Narration: Container Apps workload profile environments need a delegated subnet with a minimum /27 mask, which cannot be changed after creation; for production, start at /23.
Module 4 · Compute: VM (cloud-init) and Container Apps
- Explain Terraform → provider (gRPC
ApplyResourceChange) → ARM REST (existence-check GET → PUT → pollingAzure-AsyncOperation/Location→ final GET) → write state, and whether the resource is in state on timeout/failure. - Use Terraform to create ACR, Log Analytics,a VNet-integrated Container Apps environment (workload profile) and the myapp app: user-assigned managed identity + AcrPull passwordless pulls, external HTTPS ingress, probes, and scaling.
- (Optional) use
templatefile()+ cloud-init to deliver a Linux VM, and understand whycustom_datasome changes cause recreation. - Know the changes azurerm 5.0 made to Container Apps environments:
logs_destinationno longer computed automatically; you must set"log-analytics"to link a workspace.
What: resources delivered by this module
| Resource | Terraform type | Key points |
|---|---|---|
| Log Analytics workspace | azurerm_log_analytics_workspace | PerGB2018, 30-day retention; ACA app logs are written here |
| Container registry | azurerm_container_registry | Basic,admin_enabled = false (no admin account); the name must be globally unique, 5–50 alphanumeric characters |
| User-assigned managed identity | azurerm_user_assigned_identity | lifecycle independent of the app, so it can be authorized first, then the app created, avoiding "no permission to pull the image when the app is created" |
| Role assignment AcrPull | azurerm_role_assignment | scope = ACR,principal_type = "ServicePrincipal" |
| Container Apps environment | azurerm_container_app_environment | infrastructure_subnet_id = snet-aca; workload_profile Consumption; since 5.0 requires logs_destination = "log-analytics" |
| myapp app | azurerm_container_app | registry { server, identity }; ingress external,target_port = 5000; startup/liveness/readiness probes /healthz |
| Linux VM (optional) | azurerm_linux_virtual_machine + NIC + public IP | Ubuntu 24.04,custom_data = base64encode(templatefile(...)) |
Why: why use Terraform instead of az containerapp create
- What took more than 10 az commands in the Docker lesson is here a declaration that can be reviewed, repeated, and destroyed. Dependencies (identity → role assignment → app) are guaranteed by the dependency graph, not by script order.
- Drift is detectable: if replica count or image is changed in the portal, the next plan will show the difference.
- The same module can be copied to create dev/test/prod (Lesson 6).
How: what happens on ARM during one create (core mechanism)
- core walks the dependency graph: when
azurerm_container_app.myappall its dependencies (environment, identity, role assignment, image build) are complete, core calls the provider'sApplyResourceChange, passing prior state (null) and planned state. - Existence check: before creating, azurerm first
GETthe resource ID. A 200 response means the resource already exists but is not in state → it reports "A resource with the ID … already exists - to be managed via Terraform this resource needs to be imported into the State" (M7). Only a 404 lets it continue. - PUT:
PUT https://management.azure.com/subscriptions/{sub}/resourceGroups/rg-tf-lab/providers/Microsoft.App/containerApps/myapp?api-version=…, with a request body that is JSON the provider converted from HCL. ARM first performs authentication,RBAC authorization (requiresMicrosoft.App/containerApps/write, and referencing a managed identity also requiresMicrosoft.ManagedIdentity/userAssignedIdentities/assign/action),Azure Policy evaluation, then forwards the request to the Microsoft.App resource provider. - Long-running operation (LRO): the resource provider returns
201 Created/200or202 Accepted, withAzure-AsyncOperationorLocationheader (andRetry-After). The provider polls at the Retry-After intervalGETthis operation URL untilstatusisSucceeded/Failed/Canceled; meanwhile the CLI showsStill creating... [20s elapsed]. - Final read: on success the provider then
GETreads the resource, and fills the server-computed attributes (ingress.fqdn,latest_revision_name,outbound_ip_addresses…) into the new state and returns it to core. - Write state: core updates the in-memory state and persists it to the backend (the M2 blob; overwritten while holding the lease).
What is in state after a failure? By default, if the polling phase fails or times out (timeouts { create = "30m" } not completed within features { persist_id_on_create_before_polling_for_completion = true } ; azurerm does not write the resource ID to state, but a "half-built" resource may already exist on Azure. The next apply's existence check will hit it → requires import or manual deletion. The provider's false can write the ID before polling (default
), so after a failure the resource is marked tainted and the next apply replaces it automatically.
identity { type = "UserAssigned", identity_ids = [uami.id] } Identity chain for Container Apps pulling ACR images registry { server = acr.login_server, identity = uami.id } Attach the identity to the app; identity tell the platform to "use this identity to pull the image" (the docs require this ID to be a user-assigned identity declared in the identity block; username/password_secret_name and AcrPull are mutually exclusive). The platform uses the identity to get a token from Entra ID, then exchanges it with ACR for refresh/access tokens to pull the image—provided the identity has
.
| Linux VM + cloud-init | Azure Container Apps | |
|---|---|---|
| When: VM or Container Apps | Best for | Full OS control, special kernels/drivers, legacy software, Ansible management (Ansible Lesson 3) |
| HTTP/TCP microservices, event-driven jobs, need to scale to zero | Operations | Patching, monitoring agents, and scaling are all on you (or VMSS) |
| The platform handles nodes, TLS, scaling (KEDA), and revisions | Cost | Billed hourly by VM size; when stopped (deallocated), only disks are charged |
| Consumption: billed per vCPU·second + GiB·second + requests, with a monthly free grant | custom_data Terraform notes | A change = VM recreation; cloud-init runs only on first boot |
az containerapp revision list① "Creation complete in apply means the app is reachable" — Terraform only guarantees the ARM operation succeeded; revision health depends on probes and custom_data . ② "A system-assigned identity is simpler" — a system identity is created only when the app is created, AcrPull is not yet authorized, so the first pull fails; a user-assigned identity can be authorized in advance. ③ "cloud-init in user_data reruns automatically when changed" — cloud-init by default runs only on first boot; in azurerm user_data changes force VM replacement,Diagrams
Figure 4-1 The identity is created before the app and gets AcrPull, so the app can pull passwordlessly as soon as it is created
Animation
Core animation: the full process of terraform apply creating ca-myapp
Commands
| Core commands and parameters | Command | Purpose |
|---|---|---|
terraform apply -parallelism=N | Key parameters / notes | Controls the number of resources calling ARM concurrently (default 10) |
terraform output -raw app_url | Lower it when hitting ARM throttling (429) | -json Get the app address for curl |
az containerapp revision list -g rg-tf-lab -n ca-myapp -o table | For scripts | Check revision health and traffic |
az containerapp logs show -g rg-tf-lab -n ca-myapp --type system | Terraform success ≠ revision health | --type console System logs: image pull, probe failures |
az acr repository show-tags -n $ACR --repository myapp | View app output | -o table |
az vm list-skus -l canadacentral --size Standard_B2s -o table | Confirm the image was built and pushed | Confirm the VM size is available and unrestricted in this region |
az vm list-usage -l canadacentral -o table | Check the Restrictions column | Check vCPU quota |
variable "app_src" {
M7 quota troubleshooting
type = string
default = "~/myapp"
}
variable "app_version" {
type = string
default = "1.0.0"
}
resource "azurerm_log_analytics_workspace" "lab" {
name = "log-${var.prefix}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
sku = "PerGB2018"
retention_in_days = 30
tags = local.tags
}
resource "azurerm_container_registry" "lab" {
description = "myapp source directory (contains Dockerfile)"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
sku = "Basic"
admin_enabled = false
tags = local.tags
}
resource "azurerm_user_assigned_identity" "app" {
name = "id-myapp"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
tags = local.tags
}
resource "azurerm_role_assignment" "acr_pull" {
scope = azurerm_container_registry.lab.id
role_definition_name = "AcrPull"
principal_id = azurerm_user_assigned_identity.app.principal_id
name = "acr${var.prefix}${local.suffix}" # globally unique, alphanumeric only
}
principal_type = "ServicePrincipal" # set explicitly when creating the identity, to avoid failures from directory replication delay
resource "terraform_data" "build" {
triggers_replace = [
var.app_version,
filesha256(pathexpand("${var.app_src}/app.py")),
filesha256(pathexpand("${var.app_src}/Dockerfile")),
]
provisioner "local-exec" {
command = "az acr build -r ${azurerm_container_registry.lab.name} -t myapp:${var.app_version} ${pathexpand(var.app_src)} --no-logs"
}
}
resource "azurerm_container_app_environment" "lab" {
name = "cae-${var.prefix}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
infrastructure_subnet_id = azurerm_subnet.this["aca"].id
# Demo only: triggers a cloud build during apply. In production, image builds belong to CI (Lesson 5); Terraform only references the tag
log_analytics_workspace_id = azurerm_log_analytics_workspace.lab.id
workload_profile {
name = "Consumption"
workload_profile_type = "Consumption"
}
tags = local.tags
}
resource "azurerm_container_app" "myapp" {
name = "ca-myapp"
container_app_environment_id = azurerm_container_app_environment.lab.id
resource_group_name = azurerm_resource_group.lab.name
revision_mode = "Single"
workload_profile_name = "Consumption"
tags = local.tags
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.app.id]
}
registry {
server = azurerm_container_registry.lab.login_server
identity = azurerm_user_assigned_identity.app.id
}
ingress {
external_enabled = true
target_port = 5000
transport = "auto"
traffic_weight {
latest_revision = true
percentage = 100
}
}
template {
min_replicas = 1
max_replicas = 3
container {
name = "myapp"
image = "${azurerm_container_registry.lab.login_server}/myapp:${var.app_version}"
cpu = 0.25
memory = "0.5Gi"
env {
name = "APP_VERSION"
value = var.app_version
}
startup_probe {
transport = "HTTP"
port = 5000
path = "/healthz"
interval_seconds = 3
failure_count_threshold = 20
}
liveness_probe {
transport = "HTTP"
port = 5000
path = "/healthz"
}
readiness_probe {
transport = "HTTP"
port = 5000
path = "/healthz"
}
}
http_scale_rule {
name = "http-50"
concurrent_requests = "50"
}
}
depends_on = [azurerm_role_assignment.acr_pull, terraform_data.build]
}
output "app_url" {
value = "https://${azurerm_container_app.myapp.ingress[0].fqdn}"
}
output "acr_name" {
value = azurerm_container_registry.lab.name
}
logs_destination = "log-analytics" # must be set explicitly since 5.0 to link a workspacecurl $(terraform output -raw app_url) How to verify: Returns[1.0.0] Hello from …, hits=N/A (redis not connected) (Redis is connected in M5).target_port Common error: upstream connect error does not match the app's listening port → revision unhealthy, access returns logs_destination ; forgetting log_analytics_workspace_id causes 5.x to reject a standalone setting of . Production use: -var app_version=$GITHUB_SHA The image tag is passed in by CI (
Lab
cd ~/tf-lab3 && source ~/tf-lab3.env Write compute.tf (see the "Commands" tab), run plan to check the dependency order terraform plan -out=compute.tfplan | grep -E "will be created|Plan:"
# azurerm_container_app.myapp will be created # azurerm_container_app_environment.lab will be created # azurerm_container_registry.lab will be created # azurerm_log_analytics_workspace.lab will be created # azurerm_role_assignment.acr_pull will be created # azurerm_user_assigned_identity.app will be created # terraform_data.build will be created Plan: 7 to add, 0 to change, 0 to destroy.
time terraform apply compute.tfplan
azurerm_user_assigned_identity.app: Creation complete after 3s azurerm_container_registry.lab: Creation complete after 14s terraform_data.build: Provisioning with 'local-exec'... terraform_data.build (local-exec): Executing: ["/bin/sh" "-c" "az acr build -r acrtflabk3x9q -t myapp:1.0.0 /home/you/myapp --no-logs"] azurerm_role_assignment.acr_pull: Creation complete after 26s azurerm_container_app_environment.lab: Still creating... [2m10s elapsed] azurerm_container_app_environment.lab: Creation complete after 3m2s terraform_data.build: Creation complete after 1m5s azurerm_container_app.myapp: Still creating... [20s elapsed] azurerm_container_app.myapp: Creation complete after 38s Apply complete! Resources: 7 added, 0 changed, 0 destroyed. Outputs: acr_name = "acrtflabk3x9q" app_url = "https://ca-myapp.happysky-1a2b3c4d.canadacentral.azurecontainerapps.io"
Expected output (excerpt, times are examples) ME_… Creating a VNet-integrated environment usually takes several minutes (it creates a load balancer and public IP in the Still creating... managed resource group). Azure-AsyncOperation is the provider polling
curl -s $(terraform output -raw app_url)
curl -s $(terraform output -raw app_url)/healthz; echo
az containerapp revision list -g rg-tf-lab -n ca-myapp --query "[].{rev:name, active:properties.active, health:properties.healthState, traffic:properties.trafficWeight}" -o table
Expected output (example) ok Rev Active Health Traffic ------------------ -------- -------- --------- ca-myapp--0000001 True Healthy 100
app_version : change 1.0.1 to
terraform apply -var app_version=1.0.1 -auto-approve | grep -E "must be replaced|updated in-place|Plan:" curl -s $(terraform output -raw app_url)
# azurerm_container_app.myapp will be updated in-place # terraform_data.build must be replaced Plan: 1 to add, 1 to change, 1 to destroy. Expected output (example)
[1.0.1] Hello from ca-myapp--0000002-…, hits=N/A (redis not connected) terraform_data.build Note that in the plan app_version = "1.0.1" is a "replace" (trigger change), while the container app is updated in place — on ARM it is another PUT to the same resource, and the platform generates a new revision from it. From then on, use
#cloud-config
package_update: true
packages: [docker.io]
runcmd:
- systemctl enable --now docker
- mkdir -p /srv/www
- echo "<h1>${greeting} from $(hostname)</h1>" > /srv/www/index.html
- docker run -d --restart unless-stopped -p 80:80 -v /srv/www:/usr/share/nginx/html:ro nginx:alpine
variable "enable_vm" {
type = bool
default = false
}
resource "azurerm_public_ip" "vm" {
count = var.enable_vm ? 1 : 0
name = "pip-vm-${var.prefix}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
allocation_method = "Static"
sku = "Standard"
tags = local.tags
}
resource "azurerm_network_interface" "vm" {
count = var.enable_vm ? 1 : 0
name = "nic-vm-${var.prefix}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
ip_configuration {
name = "ipconfig1"
subnet_id = azurerm_subnet.this["vm"].id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.vm[0].id
}
}
resource "azurerm_linux_virtual_machine" "vm" {
count = var.enable_vm ? 1 : 0
name = "vm-${var.prefix}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
size = "Standard_B2s"
admin_username = "azureuser"
network_interface_ids = [azurerm_network_interface.vm[0].id]
custom_data = base64encode(templatefile("${path.module}/cloud-init.yaml.tftpl", { greeting = "Hello Terraform" }))
admin_ssh_key {
username = "azureuser"
public_key = file(pathexpand("~/.ssh/id_ed25519.pub"))
}
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "Canonical"
offer = "ubuntu-24_04-lts"
sku = "server"
version = "latest"
}
identity {
type = "SystemAssigned"
}
tags = local.tags
}
output "vm_ip" {
value = var.enable_vm ? azurerm_public_ip.vm[0].ip_address : null
}
test -f ~/.ssh/id_ed25519.pub || ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519 terraform apply -var enable_vm=true -auto-approve sleep 90; curl -s http://$(terraform output -raw vm_ip) ssh azureuser@$(terraform output -raw vm_ip) 'cloud-init status --long | head -3' (Optional, billed hourly) Linux VM + cloud-init
<h1>Hello Terraform from vm-tflab</h1> status: done extended_status: done boot_status_code: enabled-by-generator
Expected output (example) ${greeting} In the template, the templatefile() is replaced by $(hostname) on the Terraform side; az vm list-skus is not Terraform interpolation; it is passed unchanged to the shell. The public IP uses the Standard SKU (Basic SKU public IPs are retired). If the size is unavailable in your subscription/region, switch to
Production cases
Case 1: first deployment intermittently fails with "unable to pull image … unauthorized" Problem: A pipeline apply creates the identity, AcrPull, and the app in one go; occasionally the app revision provisioning fails, and rerunning fixes it. Cause: After a role assignment is written successfully, it takes time to take effect for ACR authentication (RBAC eventual consistency, can take several minutes). Fix: time_sleep (hashicorp/time, for example 60–120 seconds), or put "identity and authorization" in a separate root module that runs first. Limitation: sleep is an empirical value; the thorough fix is layering (authorize in the platform layer first, deploy the app layer later).
Case 2: resource "already exists" after apply timeout
Problem: Environment creation exceeded the default timeout due to regional capacity issues, and Terraform exited with an error; rerunning reports already exists. Fix: Check the resource state on Azure (provisioningState); if Succeeded, adopt it with import block; if Failed, delete it manually and retry. Set timeouts { create = "60m" } for resources that are very slow to create. Limitation:persist_id_on_create_before_polling_for_completion This can reduce such cases, but it causes failed resources to enter the tainted state and be replaced on the next apply; enable it only after the team understands this.
Case 3: a cloud-init change on the VM causes recreation
Problem: Someone changed a package name in the cloud-init template, and the plan showed the VM must be replaced, nearly deleting a machine holding local data. Fix: Hand configuration management on the VM to Ansible (Ansible course); keep cloud-init to minimal bootstrap; add lifecycle { prevent_destroy = true } or ignore_changes = [custom_data]; keep data on managed data disks. Limitation:ignore_changes template changes will then never take effect, so you need a matching change process.
Common errors and fixes
Failed to provision revision for container app 'ca-myapp'. Error details: … unable to pull image using Managed identity … unauthorized
Cause: The identity has no AcrPull, or it was just granted and has not taken effect yet; registry.identity points to an identity not declared in the identity block; the image tag does not exist.
az role assignment list --scope $(az acr show -n $(terraform output -raw acr_name) --query id -o tsv) -o table az acr repository show-tags -n $(terraform output -raw acr_name) --repository myapp -o tsv az containerapp logs show -g rg-tf-lab -n ca-myapp --type system --tail 30
Fix: Add the role assignment and wait for propagation (or time_sleep), confirm the tag exists, then terraform apply (failed resources are usually not in state and may need import; see M7).
Accessing the FQDN returns upstream connect error or disconnect/reset before headers / revision Unhealthy
Cause:target_port The port does not match the app's port, the app listens only on 127.0.0.1, or the probe path is wrong, causing replicas to restart repeatedly.
az containerapp revision list -g rg-tf-lab -n ca-myapp -o table az containerapp logs show -g rg-tf-lab -n ca-myapp --type console --tail 30
Fix: Bind myapp's gunicorn to 0.0.0.0:5000; make the probe port/path match the app; increase startup_probe.failure_count_threshold when startup is slow.
Error: creating Managed Environment … ManagedEnvironmentInvalidNetworkConfiguration / subnet … is too small
Cause: The subnet does not meet the environment type requirements (size, delegation), or overlaps reserved ranges.
Fix: workload profile environment: subnet ≥ /27 and delegated to Microsoft.App/environments; see M3. Subnet size cannot be changed; you can only create a new subnet and environment. Use the actual returned error code.
Error: local-exec provisioner error … az: command not found / ERROR: (AuthorizationFailed) … Microsoft.ContainerRegistry/registries/scheduleRun/action
Cause: The machine running Terraform has no az, or the current identity lacks permission to start a cloud build on ACR.
Fix: Install and sign in to az; grant sufficient permissions (Owner/Contributor includes them). This also shows the provisioner depends on an external environment; in production, builds should move to CI.
OperationNotAllowed: Operation could not be completed as it results in exceeding approved standardBSFamily Cores quota.
Cause: The vCPU quota for this VM family in this region is insufficient (common with new or free-trial subscriptions).
az vm list-usage -l canadacentral --query "[?contains(name.value,'BS')].{name:name.localizedValue, used:currentValue, limit:limit}" -o table
Fix: Switch to a VM family or region with quota, or request an increase in the portal's "Quotas" (see M7).
1. Without opening the portal, confirm ca-myapp's active revision name, health status, and the image in use.
az containerapp show -g rg-tf-lab -n ca-myapp \
--query "{rev:properties.latestReadyRevisionName, image:properties.template.containers[0].image}" -o table
az containerapp revision list -g rg-tf-lab -n ca-myapp --query "[?properties.active].{rev:name,health:properties.healthState}" -o table2. Use TF_LOG to observe the provider's polling requests for the long-running operation (URLs only).
TF_LOG=DEBUG terraform apply -auto-approve -var app_version=1.0.2 2>&1 | grep -oE "(GET|PUT) https://management.azure.com[^ ]*(containerApps|operationStatuses|containerappOperationStatuses)[^ ]*" | head
During one apply, Container App creation timed out after "Still creating... [25m elapsed]". You rerun apply and get an already exists error. Explain the cause and give the handling steps.
By default azurerm does not write the resource ID to state before polling completes; the timeout means the provider gave up waiting, but the operation on ARM keeps running, so the resource may have been created (or even succeeded). On reapply, the existence-check GET returns 200, so it reports already exists. Handling: ①az containerapp show Check provisioningState; ② when Succeeded, write import { to = azurerm_container_app.myapp id = "…/containerApps/ca-myapp" } and run plan to confirm the differences, then apply to adopt it; ③ when Failed, delete and recreate, and investigate the cause (image, permissions, quota); ④ set a longer timeouts.
Verified teaching videos
Official documentation
- azurerm_container_app · azurerm_container_app_environment
- ARM asynchronous operations (Azure-AsyncOperation / Location / Retry-After)
- Container Apps: pulling images with a managed identity
- Terraform plugin RPC (PlanResourceChange / ApplyResourceChange)
Video storyboard (about 100 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided for a video tool to generate.
Visual: in the dependency graph, identity → role assignment → container app turn green in turn.
Narration: once all dependencies are complete, the Terraform core calls the plugin's ApplyResourceChange over gRPC.
Visual: the plugin first sends GET and gets 404, then sends PUT; the request passes through ARM's authentication, RBAC, and Policy gates to reach Microsoft.App.
Narration: the plugin first confirms the resource does not exist, then sends PUT. The resource manager checks tokens, permissions, and policies, then hands off to the resource provider.
Visual: the Azure-AsyncOperation response header appears; the plugin loops GET, and the progress bar goes from InProgress to Succeeded; the terminal shows Still creating.
Narration: creation is a long-running operation. The plugin polls operation status per Retry-After; this is the Still creating you see.
Visual: the final GET returns fqdn, data flows back to core, and the state blob version increments by one. If it fails midway, the resource is not in state, and the next run shows already exists.
Narration: on success, the plugin reads the full attributes, returns them to core, and writes the state file. If it fails, the resource may already exist on Azure but not be in state.
Module 5 · Identity and secrets: managed identities, role assignments, Key Vault
- Distinguish system-assigned from user-assigned managed identities, and management-plane from data-plane roles; use
azurerm_role_assignmentto grant least privilege. - Create a RBAC-mode Key Vault (since 5.0,
rbac_authorization_enabledmust be set explicitly); grant the Terraform identity Secrets Officer and the app identity Secrets User. - Use ephemeral
random_password+azurerm_key_vault_secret.value_woto generate and write the Redis password: the value does not go into the plan or state; usevalue_wo_versionto control rotation. - Let Container Apps use Key Vault references (
secret.key_vault_secret_id+identity) to read secrets; Redis and myapp share one secret.
What: three concepts
| Concept | Description | Terraform |
|---|---|---|
| Managed identity | An Entra service principal whose credentials are managed by Azure. System-assigned: created and deleted with the resource, one-to-one; User-assigned: an independent resource that can be shared by multiple resources and authorized before its consumers are created | identity { type = "SystemAssigned" } / azurerm_user_assigned_identity |
| Role assignment | "Who (principal) has what role (role definition) at what scope." Scope is inherited: management group → subscription → resource group → resource | azurerm_role_assignment |
| Key Vault (RBAC mode) | The data plane (reading and writing secrets) is also authorized with Azure RBAC, not the legacy access policy | azurerm_key_vault + rbac_authorization_enabled = true |
The 4 roles used in this lesson (least privilege)
| Principal | Role | Scope | Purpose |
|---|---|---|---|
| id-myapp | AcrPull | ACR | Pull images (M4) |
| id-myapp | Key Vault Secrets User | Key Vault | Read secret contents (ACA Key Vault references) |
| You, running Terraform | Key Vault Secrets Officer | Key Vault | Create/update secrets (data plane) |
| You, running Terraform | Storage Blob Data Contributor | State storage account | Read/write state (M0/M2) |
Key difference: Owner/Contributor/Key Vault Contributor are management-plane roles; in RBAC mode they cannot read secret contents; even as a subscription Owner, you must assign yourself Secrets Officer for Terraform to write secrets (Owner can assign it to itself, so this lesson does it in Terraform).
Why: why sensitive is not enough
The sensitive = true from Lesson 2 only masks values in CLI output (sensitive value), but the value is still written in plaintext to the plan file and state. Anyone who can read state (M2's Blob Data Reader, PR preview identities, colleagues who downloaded state) can get the password. ephemeral values and write-only arguments solve this problem mechanically:
- ephemeral resources (since Terraform 1.10): they are temporarily "opened" on each run, and the values they produce exist only in memory for that run,and are not written to the plan or state; they can only be referenced from other ephemeral contexts (ephemeral variables/outputs, provider configuration, provisioners, write-only arguments). For example,
ephemeral "random_password"(hashicorp/random 3.7+),ephemeral "azurerm_key_vault_secret"(reads an existing secret). - write-only arguments (since Terraform 1.11): resource arguments are sent to the provider only during apply, and the provider does not store them in state; they can accept ephemeral values. azurerm's
azurerm_key_vault_secretprovidesvalue_wo, together withvalue_wo_version(an integer; a new value is sent only when it is incremented).
How: this module's data flow
ephemeral "random_password" "redis"Generate a new password on each plan/apply (in memory only).azurerm_key_vault_secret.redisThevalue_woreferences it; only when is created orvalue_wo_versionchanges does the provider PUT the value tohttps://kv-…vault.azure.net/secrets/redis-password(a new version). After that, each run generates a new random number, but the version number is unchanged, so nothing is overwritten.- Both Container Apps'
secretblocks referenceversionless_idand specifyidentity = id-myapp: the platform uses this identity to read Key Vault. The docs say a Key Vault reference can use a versioned or versionless ID; with a versionless ID, the platform periodically fetches the latest version (verified as within 30 minutes in the Docker lesson) and restarts the active revisions that reference it. - The container gets the value via
env { secret_name = "redis-password" }. State holds only the secret's ID, not the value.
When: which approach to choose
| Approach | Value in plan? | Value in state? | Use case |
|---|---|---|---|
variable { sensitive = true } → value | Yes (masked display) | Yes | Not recommended for real secrets |
resource "random_password" → value | Yes | Yes (result) | Legacy approach before Terraform 1.10 |
data "azurerm_key_vault_secret" | Yes | Yes | Legacy approach for reading an existing secret, avoiding |
ephemeral "random_password" → value_wo | No | No | Recommended in this lesson: generate and write the secret |
ephemeral "azurerm_key_vault_secret" → other *_wo or provider configuration | No | No | Read an existing secret to configure a database password or another provider |
| Bypasses Terraform entirely (the app reads Key Vault / Key Vault references at runtime) | No | No | Secrets managed by a security team or rotation system |
Comparison with other approaches
| Key Vault reference (this lesson) | ACA inline secret value | AWS Secrets Manager (Lesson 4) | |
|---|---|---|---|
| Value stored in | Key Vault, with versioning and auditing | In the Container App resource properties (also goes into state) | Secrets Manager |
| Rotation | Change the Key Vault version; the platform follows automatically | Revision restart needed after changing the value | Takes effect after ECS task restart |
| Terraform state | ID only | Contains the value | Use ephemeral + *_wo avoids it |
value_wo_version change. ③ "Using value_wo lets Terraform detect that someone changed the value in Key Vault" — no, state has no value, so Terraform cannot compare; rotation is driven by the version number. ④ "Key Vault references take effect immediately" — versionless references are refreshed periodically by the platform; for immediate effect, restart the revision or use a versioned ID and update the app. ⑤ "Purge protection must be enabled in the lab too" — once enabled, a deleted Key Vault must wait out the retention period before a same-named one can be created; disable it in the lab and enable it in production.Identity and permissions diagram
Data flow: where traces of the password are left, from generation to container
Comparator: will this value go into state?
Choose an approach to see terraform plan 's display,terraform state show 's content, and terraform state pull | grep whether plaintext can be found. The example password is a fictitious value Xk9….
Core commands and parameters
| Command / configuration | Purpose | Notes |
|---|---|---|
ephemeral "random_password" "x" { length = 32 } | Generate a random password without writing it to disk | hashicorp/random ≥ 3.7; reference ephemeral.random_password.x.result |
value_wo / value_wo_version | with write-only to write the secret, and trigger updates with an integer version | Terraform ≥ 1.11; the two are used together |
ephemeral "azurerm_key_vault_secret" "x" | Read the value of an existing secret (not written to disk) | name,key_vault_id, optional version |
az role assignment list --assignee <principalId> --all -o table | List all roles of a principal | Troubleshoot 403 |
az keyvault secret show --vault-name KV -n NAME --query value | Manually verify a secret (requires data role) | Do not run in a shared terminal |
az keyvault list-deleted -o table / az keyvault purge -n KV | List/purge soft-deleted Key Vaults | When a name conflict occurs (M8) |
terraform state pull | grep -c "$PW" | Verify the secret is not in state | 0 means pass |
variable "redis_password_version" {
description = "Increment this value to rotate the Redis password"
type = number
default = 1
}
resource "azurerm_key_vault" "lab" {
name = "kv-${var.prefix}-${local.suffix}" # 3–24 characters, globally unique
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "standard"
rbac_authorization_enabled = true # required since 5.0; replaces the removed enable_rbac_authorization
purge_protection_enabled = false # lab environment; set to true in production
soft_delete_retention_days = 7
tags = local.tags
}
resource "azurerm_role_assignment" "kv_officer_me" {
scope = azurerm_key_vault.lab.id
role_definition_name = "Key Vault Secrets Officer"
principal_id = data.azurerm_client_config.current.object_id
}
resource "azurerm_role_assignment" "kv_user_app" {
scope = azurerm_key_vault.lab.id
role_definition_name = "Key Vault Secrets User"
principal_id = azurerm_user_assigned_identity.app.principal_id
principal_type = "ServicePrincipal"
}
# RBAC eventual consistency: leave propagation time for data-plane authorization (details in M7)
resource "time_sleep" "rbac" {
create_duration = "90s"
triggers = {
officer = azurerm_role_assignment.kv_officer_me.id
user = azurerm_role_assignment.kv_user_app.id
}
}
ephemeral "random_password" "redis" {
length = 32
special = false # avoid special-character escaping issues in redis-server command-line arguments
}
resource "azurerm_key_vault_secret" "redis" {
name = "redis-password"
key_vault_id = azurerm_key_vault.lab.id
value_wo = ephemeral.random_password.redis.result
value_wo_version = var.redis_password_version
content_type = "text/plain"
depends_on = [time_sleep.rbac]
}
# import the Redis image into ACR to avoid Docker Hub rate limits (demo uses local-exec)
resource "terraform_data" "redis_image" {
triggers_replace = [azurerm_container_registry.lab.id]
provisioner "local-exec" {
command = "az acr import -n ${azurerm_container_registry.lab.name} --source docker.io/library/redis:7-alpine -t base/redis:7-alpine --force"
}
}
resource "azurerm_container_app" "redis" {
name = "ca-redis"
container_app_environment_id = azurerm_container_app_environment.lab.id
resource_group_name = azurerm_resource_group.lab.name
revision_mode = "Single"
workload_profile_name = "Consumption"
tags = local.tags
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.app.id]
}
registry {
server = azurerm_container_registry.lab.login_server
identity = azurerm_user_assigned_identity.app.id
}
secret {
name = "redis-password"
identity = azurerm_user_assigned_identity.app.id
key_vault_secret_id = azurerm_key_vault_secret.redis.versionless_id
}
ingress {
external_enabled = false
transport = "tcp"
target_port = 6379
exposed_port = 6379
traffic_weight {
latest_revision = true
percentage = 100
}
}
template {
min_replicas = 1
max_replicas = 1 # demo: single replica, no persistence; use Azure Managed Redis in production
container {
name = "redis"
image = "${azurerm_container_registry.lab.login_server}/base/redis:7-alpine"
cpu = 0.25
memory = "0.5Gi"
command = ["sh", "-c", "exec redis-server --requirepass \"$REDIS_PASSWORD\""]
env {
name = "REDIS_PASSWORD"
secret_name = "redis-password"
}
}
}
depends_on = [azurerm_role_assignment.acr_pull, time_sleep.rbac, terraform_data.redis_image]
}
Then modify M4's azurerm_container_app.myapp: add the same secret block, and add Redis connection variables to the container:
secret {
name = "redis-password"
identity = azurerm_user_assigned_identity.app.id
key_vault_secret_id = azurerm_key_vault_secret.redis.versionless_id
}
# inside template.container:
env {
name = "REDIS_HOST"
value = azurerm_container_app.redis.name # reach it by app name within the same environment
}
env {
name = "REDIS_PORT"
value = "6379"
}
env {
name = "REDIS_PASSWORD"
secret_name = "redis-password"
}
# add time_sleep.rbac to depends_on
How to verify: When accessing myapp, hits becomes an incrementing number; terraform state pull | grep -c <password> is 0. Common errors: Terraform versions below 1.11 report Unsupported argument: value_wo or write-only-related errors; forgetting Secrets Officer when writing secrets gives 403 ForbiddenByRbac. Production use: Database admin passwords and third-party API keys can use the same pattern; the docs advise using key_vault_secret_id should ignore value changes.
Lab 5: Redis password never lands in state (about 8 minutes; Key Vault is billed per operation, very low cost)
cd ~/tf-lab3 && source ~/tf-lab3.env terraform plan -out=sec.tfplan | grep -E "ephemeral|value_wo|will be|Plan:"
ephemeral.random_password.redis: Opening...
ephemeral.random_password.redis: Opening complete after 0s
ephemeral.random_password.redis: Closing...
# azurerm_container_app.myapp will be updated in-place
# azurerm_container_app.redis will be created
# azurerm_key_vault.lab will be created
# azurerm_key_vault_secret.redis will be created
+ value_wo = (write-only attribute)
+ value_wo_version = 1
# azurerm_role_assignment.kv_officer_me will be created
# azurerm_role_assignment.kv_user_app will be created
# terraform_data.redis_image will be created
# time_sleep.rbac will be created
Plan: 7 to add, 1 to change, 0 to destroy.terraform apply sec.tfplan URL=$(terraform output -raw app_url) for i in 1 2 3; do curl -s $URL; done
[1.0.1] Hello from ca-myapp--0000003-…, hits=1 [1.0.1] Hello from ca-myapp--0000003-…, hits=2 [1.0.1] Hello from ca-myapp--0000003-…, hits=3
If it shows N/A (redis not connected): wait 1–2 minutes for the Redis replica to be ready; check az containerapp logs show -n ca-redis --type system.
KV=$(terraform state show azurerm_key_vault.lab | awk -F'"' '/^ *name /{print $2; exit}')
PW=$(az keyvault secret show --vault-name $KV -n redis-password --query value -o tsv)
echo "Password length in Key Vault: ${#PW}"
terraform state pull | grep -c "$PW" || true
terraform state show azurerm_key_vault_secret.redis | grep -E "value|versionless_id"
Password length in Key Vault: 32
0
value_wo_version = 1
versionless_id = "https://kv-tflab-k3x9q.vault.azure.net/secrets/redis-password"
State contains value_wo_version and the ID, with no value. For comparison, if you use resource "random_password" + value,grep -c it outputs a number greater than 0 (you can see the comparison in the Animation tab).
terraform apply -var redis_password_version=2 -auto-approve | grep -E "value_wo_version|Plan:" az keyvault secret list-versions --vault-name $KV -n redis-password --query "length(@)" # take effect immediately (instead of waiting for the platform's periodic refresh): restart the active revisions of both apps for app in ca-redis ca-myapp; do REV=$(az containerapp show -g rg-tf-lab -n $app --query properties.latestRevisionName -o tsv) az containerapp revision restart -g rg-tf-lab -n $app --revision $REV -o none done sleep 30; curl -s $URL
~ value_wo_version = 1 -> 2 Plan: 0 to add, 1 to change, 0 to destroy. 2 [1.0.1] Hello from ca-myapp--0000003-…, hits=1
The counter restarts from 1 because the demo Redis has no persistence and data is lost on restart—this is exactly why production should use Azure Managed Redis. Write redis_password_version = 2 to terraform.tfvars to avoid the next apply reverting to 1 and triggering another rotation.
azurerm_managed_redis (the old azurerm_redis_enterprise_cluster/database was removed in 5.0). The default database access_keys_authentication_enabled defaults to false (Entra ID authentication recommended),clustering_policy defaults to OSSCluster; confirm client compatibility. SKU names such as Balanced_B0, depend on the docs and regional availability. Run destroy right after finishing.Case 1: state leak exposes database password
Problem: During troubleshooting, a colleague pasted the output of terraform state pull into a ticket, which contained the SQL admin password. Fix: Rotate immediately; refactor to use ephemeral random_password + write-only arguments to write to Key Vault (or for resources that support *_wo resources, set the admin password directly with write-only; check the provider docs). The app accesses the database via managed identity + Entra ID authentication, eliminating the password entirely. Limitation: Old passwords remain in historical state versions; clean them up per the retention policy or accept "rotated means void".
Case 2: first deployment 403 ForbiddenByRbac
Problem: The pipeline creates the Key Vault, assigns Secrets Officer to itself, and writes the secret in the same apply; the first run always gets 403, and the second succeeds. Fix: Add time_sleep; or create the Key Vault and authorization ahead in the platform layer; or use retries at the provider/resource level (azapi supports retry blocks that retry on error regex). Limitation: Propagation time is uncertain; the docs describe it as possibly several minutes.
Case 3: trade-offs of multiple apps sharing one user-assigned identity
Problem: To save effort, the team shared one UAMI across all apps, so any app could read all secrets. Fix: Split identities by "app + environment", and scope Key Vault role assignments to specific secrets (RBAC supports a single secret as scope) or split the Key Vault. Limitation: More identities mean higher management cost; generate them in bulk with a module (Lesson 6).
Common errors and fixes
Error: checking for presence of existing Secret "redis-password" … StatusCode=403 Code="Forbidden" … "ForbiddenByRbac"
Cause: The identity running Terraform has no data-plane role on Key Vault, or the role was just assigned and has not propagated.
az role assignment list --scope $(az keyvault show -n $KV --query id -o tsv) -o table
Fix: Assign Key Vault Secrets Officer; add time_sleep between the role assignment and the secret; retry apply later.
Error: Unsupported argument … An argument named "enable_rbac_authorization" is not expected here.
Cause: 5.0 removed enable_rbac_authorization, and requires rbac_authorization_enabled to be set.
Fix: Change to rbac_authorization_enabled = true.
Error: Write-only Attribute Not Allowed / Unsupported argument "value_wo" (Terraform < 1.11)
Cause: write-only arguments require Terraform 1.11+; ephemeral resources require 1.10+.
Fix: Upgrade Terraform (1.17.2 in this lesson) and declare required_version in >= 1.11. Error text varies by actual version.
Error: Invalid use of ephemeral value … Ephemeral values are not valid in "value", because it is not a write-only attribute
Cause: An ephemeral value was assigned to a regular argument (which would go into state), so Terraform rejects it.
Fix: Use the resource's *_wo argument; if the resource does not support write-only, do not let Terraform handle the value—use a Key Vault reference or read it at runtime.
ca-myapp revision failed: Failed to provision revision … unable to fetch secret 'redis-password' using Managed identity
Cause: id-myapp lacks Key Vault Secrets User, or secret.identity is not declared in the identity block, or the Key Vault firewall blocks access.
Fix: Add the role assignment and wait for propagation; confirm the identity matches; if Key Vault networking is restricted, allow trusted services or use a private endpoint (Lesson 6).
VaultAlreadyExists / ConflictError: A vault with the same name already exists in deleted state
Cause: A Key Vault with the same name destroyed earlier is in the soft-deleted state.
az keyvault list-deleted --query "[].{name:name, purge:properties.scheduledPurgeDate}" -o table
az keyvault purge -n kv-tflab-k3x9q
Fix: purge it (requires permissions, and purge protection must be off), or use features.key_vault.recover_soft_deleted_key_vaults = true (default) to let the provider recover it.
1. List all role assignments held by id-myapp and their scopes.
PID=$(az identity show -g rg-tf-lab -n id-myapp --query principalId -o tsv)
az role assignment list --assignee $PID --all --query "[].{role:roleDefinitionName, scope:scope}" -o table2. Write an ephemeral block that reads an existing Key Vault secret db-admin 's value (not stored in state).
ephemeral "azurerm_key_vault_secret" "db_admin" {
name = "db-admin"
key_vault_id = azurerm_key_vault.lab.id
}
# can only be used in ephemeral contexts such as write-only arguments, provider configuration, and ephemeral outputsAudit requirements: no secrets may appear in any Terraform state or plan file; passwords rotate every 90 days; rotation must not require code changes. Design a solution.
① When Terraform generates the secret: ephemeral random_password + azurerm_key_vault_secret.value_wo,value_wo_version passed in as a pipeline variable (for example, incremented quarterly, or taken from formatdate("YYYYQ", timestamp()) an external computed value—note that timestamp() in Terraform changes on every run, so compute it in the pipeline); ② it is better to hand rotation to Key Vault itself (rotation policy / Event Grid + Function), with Terraform creating only an empty secret or not managing the value at all; ③ apps use Key Vault references (versionless) to follow the latest version automatically; ④ in CI, scan the plan JSON (terraform show -json) to confirm it contains no known secret patterns; ⑤ state storage allows only the pipeline identity to access it.
Verified teaching videos
Official documentation
- Terraform: Ephemeral resources and write-only arguments
- azurerm_key_vault_secret (value_wo / value_wo_version) · ephemeral azurerm_key_vault_secret
- ephemeral random_password
- Key Vault RBAC guide (built-in data roles) · Container Apps secrets and Key Vault references
Video storyboard (about 90 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided for a video tool to generate.
Visual: the state file is zoomed in; the value of a sensitive variable appears in plaintext, with a red X beside it.
Narration: sensitive only masks the value on screen; the value is still written in the state file.
Visual: a glowing temporary password comes out of the ephemeral box and goes straight through the value_wo pipe into Key Vault; only an ID is left in the state file.
Narration: ephemeral values live only in memory, and write-only arguments are sent to the cloud without being written to state. The password exists only in Key Vault.
Visual: the id-myapp badge connects to ACR and Key Vault, labeled AcrPull and Secrets User.
Narration: the app uses its managed identity to read secrets and pull images, with no connection strings at all.
Visual: value_wo_version goes from one to two, and a new version appears in Key Vault.
Narration: when rotation is needed, just increment the version number.
Module 6 · Azure Verified Modules and azapi
- Understand AVM: resource modules (
avm-res-*), pattern modules (avm-ptn-*), utility modules (avm-utl-*), and the common interface (lock,role_assignments,diagnostic_settings,private_endpoints,managed_identities,tags,enable_telemetry). - Can read a module's
required_providers: recognize "AVM requiresazurerm < 5.0, and the root module requires~> 5.14" conflicts, and know that more and more AVM modules now depend only on azapi. - Can use azapi 2.x's three core objects:
azapi_resource(any resource, with body as an HCL object),azapi_update_resource(adds an attribute to an azurerm-managed resource),data "azapi_resource"(reads any attribute), and knows when to use azapi.
What: what AVM is
Azure Verified Modules is Microsoft's official IaC module program (offering both Bicep and Terraform versions); the Terraform versions are published in the public registry under the Azure namespace, with the naming rule Azure/avm-<type>-<resource provider>-<resource type>/azurerm:
| Type | Example | Purpose |
|---|---|---|
Resource module avm-res | avm-res-network-virtualnetwork,avm-res-keyvault-vault,avm-res-app-containerapp | one primary resource + common add-ons (locks, role assignments, diagnostics, private endpoints), following WAF defaults |
Pattern module avm-ptn | Landing Zone, Hub-Spoke, etc. | architecture patterns made of multiple resources (Lesson 6) |
Utility module avm-utl | region info, naming, etc. | helper-function type |
Some module versions and provider dependencies verified on 2026-11-15
| Module | Version (release date) | Provider dependency | Can coexist with an azurerm 5.x root module |
|---|---|---|---|
avm-res-network-virtualnetwork | 0.23.0 (2026-11-04) | azapi ~> 2.12 | ✓ (does not depend on azurerm) |
avm-res-app-managedenvironment | 0.6.0 (2026-10-23) | azapi ~> 2.12,time | ✓ |
avm-res-app-containerapp | 0.9.0 (2026-05-14) | azapi ~> 2.5,modtm,random | ✓ |
avm-res-storage-storageaccount | 0.11.0 (2026-11-04) | azapi ~> 2.12 | ✓ |
avm-res-keyvault-vault | 0.13.1 (2026-11-11) | azapi ~> 2.12,azurerm >= 4.81, < 5.0 | ✗ Conflict |
avm-res-containerregistry-registry | 0.9.0 (2026-10-29) | azurerm >= 4.81.0, < 5.0.0 | ✗ Conflict |
avm-res-managedidentity-userassignedidentity | 0.6.0 (2026-10-27) | azurerm >= 4.60.0, < 5.0.0 | ✗ Conflict |
Data comes from the registry.terraform.io module API. Only one azurerm version can exist in the same root module, all module constraints are intersected, and when the intersection is empty, terraform init it fails. Versions change quickly, so check the registry again before use.
What: what azapi is
Azure/azapi (latest 2.13.0 as of 2026-11) is a 'thin' provider maintained by Microsoft: it does not write a dedicated schema for each resource type, but lets you write ARM resource types, api-versions and request bodies directly,new APIs are usable on the day they are released. In 2.x, the body is an HCL object (no longer needs jsonencode), built-in schema validation per api-version (schema_validation_enabled, default true), supports response_export_values exported attributes,sensitive_body (write-only),retry (retry on error regex),replace_triggers_refs etc.
Why: why they are needed
- AVM: unified secure defaults and interfaces, so each team does not have to write its own Key Vault module; Microsoft keeps up with API and WAF recommendations.
- azapi: azurerm usually lags in supporting new properties; for preview features, niche resources, or resources with defects in azurerm, azapi is the official escape hatch. That is also why more and more AVM modules are being rewritten as pure azapi implementations, decoupled from major azurerm releases.
How: how azapi resources are addressed
| Parameter | Meaning | Example |
|---|---|---|
type | <resource type>@<api-version> | Microsoft.App/managedEnvironments@2024-03-01 |
parent_id | Parent resource ID (resource group, subscription, or parent resource) | azurerm_resource_group.lab.id |
name / location | Resource name and region | |
body | ARM request body (HCL object) | { properties = { … } } |
response_export_values | Path exported from the response; the result is in .output | ["properties.defaultDomain"] |
When: selection rules
| Situation | Choice |
|---|---|
| azurerm fully supports it and the team is familiar with it | azurerm resource (most readable, clear plan diffs) |
| Needs enterprise-grade defaults and multiple supporting resources, and the module's provider constraints are compatible with yours | AVM resource module (pin an exact version; 0.x versions may have breaking changes) |
| azurerm lacks a certain attribute | azurerm resource + azapi_update_resource patch (make sure the two do not manage the same attribute) |
| New resource type / preview API / not yet supported by azurerm | azapi_resource |
| Only need to read an attribute (azurerm does not export it) | data "azapi_resource" |
| Call a POST action (such as list keys, restart) | azapi_resource_action (or the ephemeral version, to avoid writing returned keys into state) |
version = "0.23.0" to exact versions like this and read the changelog. ② “Using azapi means there are no plan diff hints”: azapi compares the body with the remote response, and together with schema validation it can likewise catch field errors in the plan phase. ③ “It doesn't matter if azurerm and azapi manage the same resource”: when two providers write the same attribute, it drifts back and forth; azapi_update_resource use it only for attributes azurerm does not manage. ④ “AVM telemetry uploads my configuration”: enable_telemetry default is true; it counts module usage (via the modtm provider or deployment-name tags) and can be set to false. Refer to the AVM documentation for details.Three paths lead to the same ARM
Version constraint intersection: why init fails
Interactive wizard: azurerm, azapi, or AVM?
Answer a few questions and the wizard gives a recommended approach and an example code skeleton. The rules come from the selection table in this module's “Theory” section.
Core commands and flags
| Command | Purpose | Notes |
|---|---|---|
terraform init | Downloads modules and providers, resolves version constraints | Reports errors on conflict no available releases match the given constraints |
terraform providers | Lists the provider constraint tree by module | Finds which module requires it < 5.0 |
curl -s https://registry.terraform.io/v1/modules/Azure/<m>/azurerm | Checks the latest module version and dependencies | View root.provider_dependencies |
az provider show -n Microsoft.App --query "resourceTypes[?resourceType=='managedEnvironments'].apiVersions" -o tsv | Lists the api-versions available for a resource type | Chooses a version for azapi |
terraform state show 'module.vnet.azapi_resource.vnet' | Views resources inside a module | Addresses follow state list as authoritative. |
# Separate directory ~/tf-lab3-avm (does not affect the main lab); local state is fine
terraform {
required_version = ">= 1.11"
required_providers {
azurerm = { source = "hashicorp/azurerm", version = "~> 5.14" }
azapi = { source = "Azure/azapi", version = "~> 2.13" }
}
}
provider "azurerm" {
features {}
}
provider "azapi" {}
resource "azurerm_resource_group" "avm" {
name = "rg-tf-lab-avm"
location = "canadacentral"
}
module "vnet" {
source = "Azure/avm-res-network-virtualnetwork/azurerm"
version = "0.23.0" # 0.x: pin an exact version
name = "vnet-avm"
location = azurerm_resource_group.avm.location
parent_id = azurerm_resource_group.avm.id # for pure-azapi modules, use parent_id
address_space = ["10.40.0.0/16"]
enable_telemetry = false
subnets = {
aca = {
name = "snet-aca"
address_prefixes = ["10.40.0.0/23"]
delegations = [{
name = "aca"
service_delegation = { name = "Microsoft.App/environments" }
}]
}
vm = {
name = "snet-vm"
address_prefixes = ["10.40.2.0/24"]
}
}
}
output "subnet_ids" {
value = { for k, s in module.vnet.subnets : k => s.resource_id }
}
# 1) Read an attribute that azurerm does not export
data "azapi_resource" "myapp" {
type = "Microsoft.App/containerApps@2024-03-01"
resource_id = azurerm_container_app.myapp.id
response_export_values = ["properties.latestReadyRevisionName", "properties.provisioningState", "properties.eventStreamEndpoint"]
}
output "myapp_runtime" {
value = data.azapi_resource.myapp.output.properties
}
# 2) Create a resource directly from an ARM request body (illustrative: use azapi to declare a standalone Container Apps environment)
# resource "azapi_resource" "cae2" {
# type = "Microsoft.App/managedEnvironments@2024-03-01"
# name = "cae-azapi"
# parent_id = azurerm_resource_group.lab.id
# location = azurerm_resource_group.lab.location
# body = {
# properties = {
# workloadProfiles = [{ name = "Consumption", workloadProfileType = "Consumption" }]
# appLogsConfiguration = {
# destination = "log-analytics"
# logAnalyticsConfiguration = {
# customerId = azurerm_log_analytics_workspace.lab.workspace_id
# sharedKey = azurerm_log_analytics_workspace.lab.primary_shared_key # Note: this goes into state; you can use sensitive_body instead
# }
# }
# }
# }
# response_export_values = ["properties.defaultDomain", "properties.staticIp"]
# }
# 3) Add a property that azurerm does not yet support to a resource azurerm manages (pattern only; check the API reference for the exact property name)
# resource "azapi_update_resource" "env_patch" {
# type = "Microsoft.App/managedEnvironments@<api-version>"
# resource_id = azurerm_container_app_environment.lab.id
# body = { properties = { <property not managed by azurerm> = … } }
# }
How to verify:terraform output myapp_runtime Show the revision name and Succeeded. Common errors: If the api-version is wrong, azapi fails with a schema validation error during the plan phase; response_export_values Path casing must match the ARM response. Production use: Wrap azapi resources in a module and note in a comment “move back once azurerm supports it”; when migrating, use moved blocks (Terraform 1.8+ supports moved across resource types, provided the provider implements state migration; when unsupported, use removed + import).
Lab 6: AVM VNet + azapi reads ACA attributes + reproduce a version conflict (about 7 minutes, cost ≈ 0)
mkdir -p ~/tf-lab3-avm && cd ~/tf-lab3-avm # Write avm-demo/main.tf from the Commands tab source ~/tf-lab3.env terraform init && terraform apply -auto-approve terraform state list
- Downloading registry.terraform.io/Azure/avm-res-network-virtualnetwork/azurerm 0.23.0 for vnet...
- Installing azure/azapi v2.13.0...
...
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Outputs:
subnet_ids = {
"aca" = "/subscriptions/…/resourceGroups/rg-tf-lab-avm/providers/Microsoft.Network/virtualNetworks/vnet-avm/subnets/snet-aca"
"vm" = "/subscriptions/…/subnets/snet-vm"
}
azurerm_resource_group.avm
module.vnet.azapi_resource.vnet
module.vnet.module.subnet["aca"].azapi_resource.subnet
module.vnet.module.subnet["vm"].azapi_resource.subnetcat >> main.tf <<'EOF'
module "kv" {
source = "Azure/avm-res-keyvault-vault/azurerm"
version = "0.13.1"
name = "kv-avm-demo-001"
location = azurerm_resource_group.avm.location
resource_group_name = azurerm_resource_group.avm.name
tenant_id = "00000000-0000-0000-0000-000000000000"
}
EOF
terraform init 2>&1 | tail -8
│ Error: Failed to query available provider packages │ │ Could not retrieve the list of available versions for provider │ hashicorp/azurerm: no available releases match the given constraints │ >= 4.81.0, < 5.0.0, ~> 5.14
This is the most common AVM problem in the second half of 2026. To handle it: delete this module block (in this lab), or use it in a root module that still uses azurerm 4.x; and follow the module repository's upgrade plan. Module input parameters follow its registry documentation; here they are only used to trigger version resolution.
python3 - <<'EOF'
import re,io
s=open("main.tf").read(); s=s[:s.index('module "kv"')]; open("main.tf","w").write(s)
EOF
terraform init -upgrade=false >/dev/null && echo "init OK"cd ~/tf-lab3
# In required_providers in versions.tf, add: azapi = { source = "Azure/azapi", version = "~> 2.13" }
# Write part 1 of azapi-demo.tf
terraform init -upgrade && terraform apply -auto-approve
terraform output myapp_runtime
myapp_runtime = {
"eventStreamEndpoint" = "https://canadacentral.azurecontainerapps.dev/subscriptions/…/eventstream"
"latestReadyRevisionName" = "ca-myapp--0000003"
"provisioningState" = "Succeeded"
}az provider show -n Microsoft.App --query "resourceTypes[?resourceType=='containerApps'].apiVersions | [0][:6]" -o tsv
Prefer the latest non-preview version; preview versions may change at any time, so evaluate them before production use.
cd ~/tf-lab3-avm && terraform destroy -auto-approve
Case 1: the platform team uses AVM to unify the Key Vault baseline
Problem: Each business line writes its own Key Vault; some did not enable purge protection, and some left public network access on. Approach: The platform team wraps an internal module that calls the AVM resource module and pins security parameters (RBAC, purge protection, private endpoints, diagnostic settings), exposing only a few variables; Renovate/Dependabot monitors new AVM versions and upgrades only after the plan passes in the test environment. Limitations: AVM's provider constraints propagate to all consumers, so when the platform module upgrades a major azurerm version, it must be coordinated across all of them.
Case 2: azurerm does not yet support a new property
Problem: Container Apps introduced a new environment-level setting the team urgently needs, but azurerm has no corresponding field yet. Approach: Keep the azurerm resource and add a azapi_update_resource that writes only this property, and remove the azapi patch once azurerm supports it (removing azapi_update_resource does not roll back the remote property; you need to explicitly set the same value in azurerm before removing the patch). Limitations: Make sure azurerm does not treat this property as drift and reset it.
Case 3: migrating from azurerm to a pure-azapi AVM module
Problem: The team wants to upgrade to azurerm 5.x, but the old AVM VNet module uses azurerm resources internally, and the new version switches to azapi. Approach: Read the module upgrade notes and use the provided moved/import guidance; run plan in a test subscription to confirm only “moved” or “import” operations and no destroys; for critical resources such as networking, add prevent_destroy. Limitations: State migration across providers depends on the module author providing a solution; don't assume it.
Common errors and fixes
Error: Failed to query available provider packages … hashicorp/azurerm: no available releases match the given constraints >= 4.81.0, < 5.0.0, ~> 5.14
Cause: A module (usually AVM) requires azurerm 4.x, while the root module requires 5.x.
terraform providers # see which module declares < 5.0
Fix: Switch to a pure-azapi module version or wait for an upgrade; or move the resource into a separate root module that still uses 4.x; or implement it directly with azurerm resources.
Error: embedded schema validation failed: the argument "body" is invalid: `properties.workloadProfile` is not expected here. Do you mean `properties.workloadProfiles`?
Cause: azapi validates the body against the schema of the selected api-version; the field name, hierarchy, or casing is wrong.
Fix: Check ARM template referencein that api-version's definition and correct it; when a bypass is truly needed (for example, a new field has not yet entered the built-in schema), set schema_validation_enabled = false. The exact error text depends on the actual version.
NoRegisteredProviderFound: No registered resource provider found for location 'canadacentral' and API version '2099-01-01' for type 'containerApps'
Cause: The api-version does not exist or is not supported in that region.
az provider show -n Microsoft.App --query "resourceTypes[?resourceType=='containerApps'].{v:apiVersions, l:locations}" -o json
Fix: Choose a version that appears in the list.
Error: Unsupported argument "resource_group_name" … module "vnet"
Cause: After the AVM module switches to an azapi implementation, its input changes from resource_group_name to parent_id (resource group ID), etc.; interfaces change between 0.x versions.
Fix: Read the Inputs on that version's registry page; pin the exact version and read the changelog before upgrading.
Every plan shows a diff in the azapi_resource body (permanent drift)
Cause: The server normalizes some values (casing, filling in defaults) or does not return write-only fields.
Fix: Use ignore_casing,ignore_missing_property (check the docs for default behavior),ignore_body_changes to specify the path; or write the body in the canonical form the server returns.
1. Use one command to find the provider constraints that the latest version of Azure/avm-res-keyvault-vault depends on.
curl -s https://registry.terraform.io/v1/modules/Azure/avm-res-keyvault-vault/azurerm \ | python3 -c "import sys,json;d=json.load(sys.stdin);print(d['version'],[p['name']+' '+p['version'] for p in d['root']['provider_dependencies']])"
2. Write a data source that uses azapi to read the Key Vault's properties.vaultUri and properties.enableRbacAuthorization.
data "azapi_resource" "kv" {
type = "Microsoft.KeyVault/vaults@2023-07-01"
resource_id = azurerm_key_vault.lab.id
response_export_values = ["properties.vaultUri", "properties.enableRbacAuthorization"]
}
# data.azapi_resource.kv.output.properties.vaultUriThe team wants to adopt AVM across the board and also upgrade to azurerm 5.x as soon as possible. Give an assessment and rollout steps.
① Inventory the AVM modules you plan to use and their provider_dependencies, distinguish pure-azapi modules (usable directly) from modules that still constrain azurerm < 5.0; ② split root modules by lifecycle (networking / identity / applications), keeping the root module that holds the conflicting module on 4.81 for now and upgrading the rest to 5.x; ③ pin all modules to exact versions, track them with Renovate, and merge only after the plan in a test subscription shows no breaking changes; ④ watch the azurerm 5.0 upgrade guide for removed resources (such as azurerm_redis_enterprise_*), and find alternatives; ⑤ for interface changes in 0.x modules, reserve moved/import migration time.
Verified instructional videos
Official documentation
- Azure Verified Modules official site · Terraform quick start
- azapi provider documentation · Microsoft Learn: AzAPI provider overview
- ARM template/resource type reference (choose an api-version)
Video storyboard script (about 75 seconds)
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided for a video tool to produce it.
Visual: three paths, azurerm, AVM and azapi, converge on the same ARM icon.
Narration: all three approaches ultimately call the same resource manager API; the difference is who maintains the fields and versions.
Visual: two version range bars [5.14, 6.0) and [4.81, 5.0) do not overlap, and a red “no available releases” appears.
Narration: a root module can have only one azurerm version; module constraints are intersected, and if the intersection is empty, initialization fails.
Visual: azapi_resource code, with the api-version after type highlighted.
Narration: for new features azurerm does not yet support, you can use azapi to write the resource type and API version directly, and use them the same day.
Module 7 · Cloud troubleshooting in practice
- Read the structure of azurerm error messages:
Error: creating X (Subscription: … Resource Group Name: …)+unexpected status 4xx+ ARM error codes (AuthorizationFailed,MissingSubscriptionRegistration,OperationNotAllowed…). - Handle six high-frequency failures: authentication failure, 403 insufficient permissions, resource already exists and needs import, insufficient quota, resource provider not registered, and eventual consistency of role assignments/RBAC (
PrincipalNotFound,ForbiddenByRbac). - Use
TF_LOG,az monitor activity-log list,az role assignment list,az vm list-usage, andimportblocks to locate and fix issues.
What: which layer the error comes from
| Layer | Typical errors | HTTP | Reported by | What to check first |
|---|---|---|---|---|
| ① Authentication (acquiring a token) | subscription ID could not be determined,AADSTS…,az: not found | — | provider local / Entra ID | env | grep ARM_,az account show |
| ② Authorization (RBAC / Policy) | AuthorizationFailed,RequestDisallowedByPolicy,ForbiddenByRbac | 403 | ARM / data plane | the action and scope in the error; az role assignment list |
| ③ Subscription capability | MissingSubscriptionRegistration,NoRegisteredProviderFound | 409/400 | ARM | az provider show |
| ④ Capacity / quota | OperationNotAllowed … exceeding approved … quota,SkuNotAvailable,MaxNumberOfRegionalEnvironmentsInSubExceeded | 409/400 | resource provider | az vm list-usage,az vm list-skus |
| ⑤ Resource conflict | already exists - to be managed via Terraform this resource needs to be imported,StorageAccountAlreadyTaken,VaultAlreadyExists | 200 (existence check) / 409 | provider / RP | Who created the resource? Was it soft-deleted? |
| ⑥ Eventual consistency | PrincipalNotFound, first ForbiddenByRbac, image pull unauthorized | 400/403 | ARM / data plane | Does a rerun succeed? Was the identity/role just created? |
| ⑦ Long-running operation failure | polling after Create: … Failed, timeout | — | RP async result | activity log, the resource's provisioningState |
Why: why troubleshooting in the cloud is harder
- Terraform only relays ARM errors; the real cause is in the ARM error code and message. The same symptom (403) can come from the management plane or the data plane.
- Azure is a distributed system: newly created service principals and role assignments take time to replicate globally,“first attempt fails, second attempt succeeds” is a typical signal of eventual consistency.
- A failed apply can leave resources that exist in Azure but not in state (the core animation in M4).
How: standard handling for the six failure types
| Failure | Root cause | Fix | Prevention |
|---|---|---|---|
| Authentication failure | No subscription, CLI session expired, OIDC subject mismatch | Set ARM_SUBSCRIPTION_ID,az login, fix the federated credential | In CI, use ARM_USE_CLI=false, which makes errors more direct. |
| 403 AuthorizationFailed | The identity lacks the action listed in the error (for example Microsoft.Authorization/roleAssignments/write) | Grant the minimum role per action (RBAC Administrator / User Access Administrator) | Prepare a reviewed custom role for the pipeline identity |
| Already exists, needs import | Created manually in the portal, resources left by a previous failed apply, managed by another state | import block + confirm in plan that there are no destructive changes | Prohibit write permissions in the portal; persist_id_on_create_before_polling_for_completion |
| Quota | vCPU quota for a VM family in the region, ACA environment count, etc. | Change SKU/region, or request a quota increase | Check before go-live list-usage; pre-request in the Landing Zone |
| RP not registered | 5.0 does not register RPs by default | az provider register or resource_providers_to_register | register in the subscription provisioning process |
| Eventual consistency | New service principal not yet replicated, role assignment not yet effective | Set the role assignment principal_type; add time_sleep; rerun | Put identity and authorization in a layer that runs first |
azurerm_role_assignment Docs note: when creating role assignments for newly created principals, you must explicitly set principal_type; there is also skip_service_principal_aad_check (applies only to service principals) to skip directory checks that may fail due to replication delay.
When: which tool to use when
- The error message is clear enough (in most cases): handle it directly by error code; see the troubleshooting tree below.
- Not sure what the request body is:
TF_LOG=DEBUG TF_LOG_PATH=tf.log, search forPUT https://management.azure.comto view the JSON sent (logs contain sensitive information such as token fragments; delete them after use). - Async failure:
az monitor activity-log list --resource-group rg-tf-lab --status Failedcheck the detailed reason returned by the RP. - “exists in Azure, not in state”:
importblock (Terraform 1.5+); 1.7+ supports usingfor_each.
-target use it only in emergencies; long-term use leaves state out of sync with configuration. ④ “If a rerun succeeds, it's fine”: an occasional failure indicates a race condition that should be handled explicitly in code (time_sleep, layering), otherwise it will reappear in CI next time.“Layered diagnosis” of a failed request
import fix workflow
Simulator: role assignment propagation race
Within the same apply: create identity → create role assignment → use the permission immediately (write Key Vault secret / pull image). Drag the “propagation delay” slider and toggle whether to use principal_type and time_sleep, to see whether apply succeeds. The delay is illustrative; actual propagation time is uncertain (usually tens of seconds to several minutes).
Troubleshooting toolbox
| Command | Purpose | Notes |
|---|---|---|
TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform apply | Record the full interaction between provider and ARM | TF_LOG_PROVIDER Log provider only; logs are sensitive |
az monitor activity-log list -g rg-tf-lab --status Failed --offset 1h | View failed ARM operations and detailed reasons | --query "[].{op:operationName.value,msg:properties.statusMessage}" |
az role assignment list --assignee ID --all | View all roles of a principal | On 403, verify the scope |
az provider show -n NS --query registrationState | RP registration status | Wait while Registering |
az vm list-usage -l LOC / az quota list | Quota usage | az quota Requires an extension; see the documentation |
az vm list-skus -l LOC --size X --query "[].restrictions" | Whether the SKU is restricted | NotAvailableForSubscription |
az resource show --ids ID --query properties.provisioningState | Actual state of the resource after an async failure | Decide whether to import or delete |
terraform plan -generate-config-out=gen.tf | Automatically generate a configuration draft for import blocks | Terraform 1.5+; needs manual cleanup |
# Take over a resource created manually in the portal (Terraform 1.5+; 1.7+ can be combined with for_each)
import {
to = azurerm_log_analytics_workspace.manual
id = "/subscriptions/<sub>/resourceGroups/rg-tf-lab/providers/Microsoft.OperationalInsights/workspaces/log-manual"
}
resource "azurerm_log_analytics_workspace" "manual" {
name = "log-manual"
location = "canadacentral"
resource_group_name = azurerm_resource_group.lab.name
sku = "PerGB2018"
retention_in_days = 30
}
terraform plan | grep -E "import|Plan:"
# Expected: Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
az monitor activity-log list -g rg-tf-lab --status Failed --offset 2h \
--query "[].{time:eventTimestamp, op:operationName.value, msg:properties.statusMessage}" -o jsonc | head -40
Lab 7: deliberately create 4 failures and fix them (about 10 minutes, cost ≈ 0)
cd ~/tf-lab3 && source ~/tf-lab3.env az monitor log-analytics workspace create -g rg-tf-lab -n log-manual -l canadacentral -o none # First write only the resource block (no import block), then apply: terraform apply -auto-approve 2>&1 | grep -A2 "already exists"
│ Error: A resource with the ID "/subscriptions/…/resourceGroups/rg-tf-lab/providers/Microsoft.OperationalInsights/workspaces/log-manual" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_log_analytics_workspace" for more information.
Add the import block from the Commands tab, then plan / apply:
terraform plan | grep -E "will be imported|Plan:" terraform apply -auto-approve | tail -1
# azurerm_log_analytics_workspace.manual will be imported Plan: 1 to import, 0 to add, 0 to change, 0 to destroy. Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
After a successful import you can delete the import block (keeping it is harmless). Deleting the resource block at the end will make Terraform destroy the resource; this is exactly how we clean up here: delete the block, then apply.
SP=$(az ad sp create-for-rbac -n sp-tflab-contrib --role Contributor \ --scopes /subscriptions/$ARM_SUBSCRIPTION_ID/resourceGroups/rg-tf-lab -o json) export ARM_CLIENT_ID=$(echo $SP | jq -r .appId) ARM_CLIENT_SECRET=$(echo $SP | jq -r .password) ARM_TENANT_ID=$(echo $SP | jq -r .tenant) terraform plan -refresh=false -replace=azurerm_role_assignment.acr_pull -out=x.tfplan >/dev/null terraform apply x.tfplan 2>&1 | grep -E "AuthorizationFailed" | head -2 unset ARM_CLIENT_ID ARM_CLIENT_SECRET ARM_TENANT_ID az ad sp delete --id $(echo $SP | jq -r .appId)
│ unexpected status 403 (403 Forbidden) with error: AuthorizationFailed: The client '…' with object id '…' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/…/resourceGroups/rg-tf-lab/providers/Microsoft.ContainerRegistry/registries/acrtflabk3x9q/providers/Microsoft.Authorization/roleAssignments/…' or the scope is invalid. If access was recently granted, please refresh your credentials.
Note: the service principal must also be able to read state (M2's Storage Blob Data Contributor), otherwise you will get a 403 earlier at the backend. This step uses a client secret for demonstration only; delete the service principal immediately afterward. Replacing the role assignment briefly removes AcrPull; if it fails midway, use your own identity to rerun terraform apply to restore.
az provider list --query "[?registrationState=='NotRegistered'].namespace | [?contains(@,'Microsoft.')] | [:8]" -o tsv
│ unexpected status 409 (409 Conflict) with error: MissingSubscriptionRegistration: The subscription is not registered to use namespace 'Microsoft.App'. See https://aka.ms/rps-not-found for how to register subscriptions.
Fix: az provider register -n Microsoft.App --wait, or the provider block's resource_providers_to_register. Do not unregister RPs in a production subscription just for the demo.
az vm list-usage -l canadacentral --query "[?currentValue>\`0\` || contains(name.value,'BS')].{name:name.localizedValue,used:currentValue,limit:limit}" -o table
az vm list-skus -l canadacentral --size Standard_B2s --query "[].{name:name, restrictions:restrictions[].reasonCode}" -o table
Name Used Limit -------------------------------- ------ ------- Total Regional vCPUs 0 10 Standard BS Family vCPUs 0 10 Name Restrictions ------------ -------------- Standard_B2s []
limit is 0 or restrictions contains NotAvailableForSubscription then change the SKU/region, or request an increase on the portal's “Quotas” page.
terraform plan -detailed-exitcode; echo "exit=$?" # 0 = no changes, 2 = changes present
Case 1: pipeline intermittently hits PrincipalNotFound
Problem: A UAMI is created for each new application and the role is assigned immediately; about 1 in 5 runs report PrincipalNotFound: Principal … does not exist in the directory …. Approach: Add principal_type = "ServicePrincipal" (official documentation says it must be set explicitly when creating new principals); the failure rate dropped to zero. Limitations: Data-plane permissions still take time to take effect; resources that use the permissions later still need time_sleep or layering.
Case 2: Azure Policy denies deployment
Problem: apply reports RequestDisallowedByPolicy: Resource 'kv-…' was disallowed by policy. Policy identifiers: '…Key vaults should have deletion protection enabled…'. Approach: Rather than requesting an exemption, satisfy the policy (enable purge protection); in the plan phase, use azurerm 5.x's preflight_enabled (supported for some resources) or Terraform Policy (GA in 1.17, Lesson 5) to catch it early. Limitations: Preflight covers only some resources, and values known only after apply cannot be validated.
Case 3: locating an async failure with the activity log
Problem: The ACA environment failed 20 minutes after creation, and Terraform only showed a generic error. Approach:az monitor activity-log list --status Failed Found the detailed message: a conflict between the subnet and the UDR forced tunnel made outbound dependencies unreachable. Fixed the route table, then rebuilt. Limitations: The activity log is retained for 90 days by default; for long-term auditing, export it to Log Analytics.
Interactive troubleshooting tree: terraform apply failed on Azure
Select the symptom you see as prompted, and step through to the cause, diagnostic commands, and fix.
Additional: other common errors
StorageAccountAlreadyTaken: The storage account named sttfstate… is already taken.
Cause: Storage account / ACR / Key Vault names are globally unique. Fix: Add random_string suffix to the name (this lesson's local.suffix).
Error: deleting Resource Group "rg-tf-lab": the Resource Group still contains Resources.
Cause:prevent_deletion_if_contains_resources = true (default), and the group contains resources Terraform does not manage (for example, ones created manually in the portal or supporting resources automatically created by ACA). Fix: Check az resource list -g rg-tf-lab -o table, import or delete it manually and retry (M8).
429 TooManyRequests / RetryableError: … throttled
Cause: ARM throttling (large numbers of concurrent reads and writes). Fix: The provider retries according to Retry-After; for large-scale configurations, use -parallelism=5, split root modules, and reduce unnecessary refresh (Terraform 1.17's -minimal-refresh option refreshes only resources with changes).
1. List the failed ARM operations and their messages in rg-tf-lab over the last 1 hour.
az monitor activity-log list -g rg-tf-lab --status Failed --offset 1h \
--query "[].{op:operationName.value, msg:properties.statusMessage}" -o jsonc2. For the existing Key Vault kv-legacy write an import block and generate a configuration draft.
cat > import-kv.tf <<'EOF'
import {
to = azurerm_key_vault.legacy
id = "/subscriptions/<sub>/resourceGroups/rg-tf-lab/providers/Microsoft.KeyVault/vaults/kv-legacy"
}
EOF
terraform plan -generate-config-out=generated.tfThe first full configuration run in a new subscription first reports MissingSubscriptionRegistration; after registration it reports OperationNotAllowed (quota); after changing the SKU it reports ForbiddenByRbac; then a rerun succeeds completely. Explain each one, and describe how to make the next new subscription succeed on the first try.
① azurerm 5.0 does not register RPs by default, so a new subscription lacks registrations such as Microsoft.App; ② new or trial subscriptions have low or zero vCPU quota for some VM families; ③ the Key Vault role assignment created in the same apply has not yet propagated (eventual consistency), and it is in effect by the time of the rerun. Prevention: register the required RPs and pre-request quota in the subscription provisioning process; in the configuration, set principal_type on role assignments and add time_sleep before data-plane operations, or split the identity/authorization layer and the application layer into two root modules deployed in order.
Verified instructional videos
Official documentation
- Common Azure deployment error codes
- Azure RBAC troubleshooting (including propagation delay)
- Terraform import block · TF_LOG debugging
- View and request quotas
Video storyboard script (about 80 seconds)
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided for a video tool to produce it.
Visual: a red error message is split into three parts: resource, HTTP status, ARM error code.
Narration: read the error code first; it tells you whether the request is stuck at authentication, authorization, subscription, quota, or the resource provider.
Visual: on the timeline, after the role assignment is created, there is a gray delay before the permission takes effect; requests during that period turn red.
Narration: a first-attempt failure followed by a second-attempt success is usually eventual consistency. Set the principal type, and wait before using the permission.
Visual: already exists error → import block → plan shows 1 to import → apply succeeds.
Narration: when a resource already exists, don't rush to delete it; first take it over with an import block, and confirm the plan has no destroys.
Module 8 · Cost, cleanup and self-check
- List how each resource in this lesson is billed, and estimate the cost of one lab run; use tags and budgets (
azurerm_consumption_budget_resource_group) to control costs. - Understand
terraform destroy's execution order (reverse dependency graph) and how the providerfeaturesaffects deletion behavior (Key Vault purge, resource group non-empty protection, Log Analytics soft delete). - Thorough cleanup: lab resources, AVM demo, managed resource groups, soft-deleted Key Vaults, Network Watcher, and (after the entire course ends) the state storage account.
What: billing points for this lesson's resources
| Resource | Billing model | Usage in this lesson | Notes |
|---|---|---|---|
| Container Apps (Consumption configuration) | Billed per vCPU-second, GiB-second and request count; each subscription gets a monthly free allowance (official: 180,000 vCPU-seconds, 360,000 GiB-seconds, 2 million requests; subject to the pricing page) | 2 apps × 0.25 vCPU / 0.5 GiB, min_replicas = 1 | Always-on replicas keep consuming the allowance; when not in use, set min_replicas = 0 (not suitable for Redis) |
| Managed resources of the VNet-integrated environment | ME_… Standard load balancer and standard public IP in the resource group | 1 set | Official docs say this part is billed separately from Container Apps |
| ACR Basic | Fixed daily charge + storage | 1 | Billed daily even when unused |
| Log Analytics | Billed per GB ingested (PerGB2018) and retention | Very little | Nearly zero in a demo environment |
| Key Vault Standard | Billed per operation | Very little | negligible |
| Storage account (state) | Capacity + transactions; ZRS costs more than LRS | A few KB | negligible; keep until the end of the course |
| Linux VM (optional) | Billed per second by size + managed disk + standard public IP | Delete after finishing | “Stopped” does not mean “deallocated”; only deallocated VMs stop incurring compute charges |
| Azure Managed Redis (optional) | Billed per instance-hour | Delete after finishing | The most expensive optional item in this lesson |
Unit prices vary by region, currency and agreement, so this lesson does not hard-code prices; use the Pricing Calculator or az consumption usage list (when your subscription type supports it) to check. The estimator on the Animation tab uses illustrative unit prices.
Why: why there may still be charges or leftovers after destroy
- Things Terraform does not manage: when a VNet is created, Azure may enable Network Watcher in
NetworkWatcherRGautomatically; ACA, inME_…the managed resource group, creates load balancers (deleted with the environment); resources created manually in the portal. - Soft delete: Key Vault (in this lesson,
purge_soft_delete_on_destroy = truewill be purged on destroy; with purge protection on it cannot be purged); Log Analytics workspaces are soft-deleted for 14 days by default (features.log_analytics_workspace.permanently_delete_on_destroydefault false); blob/container soft delete in storage. - Independent lifecycle: the state storage account is in
rg-tfstate, and has aCanNotDeletelock; the lab's destroy won't delete it. This is intentional.
How: destroy execution order
terraform destroy (equivalent to terraform apply -destroy), refresh first, then follow the dependency graph in reverse order Deletion: first delete those that depend on others (Container App), then those being depended on (environment, subnet, VNet, resource group). Each deletion is also an ARM long-running operation (DELETE → polling). features.resource_group.prevent_deletion_if_contains_resources = true when enabled, if the resource group still contains resources Terraform does not know about, deleting the group fails instead of cascading. This is protection, not a fault.
When: cleanup strategy
- At the end of each study session: run
terraform destroy; rebuild with apply the next day (all resources in this lesson can be rebuilt within 10 minutes). - Team lab subscription: tag resources with
owner/expirestags, combined with budget alerts and scheduled cleanup scripts (Lesson 5 automation). - Whole course finished: delete
rg-tfstate(delete the lock first), clean upNetworkWatcherRG(if it was created in this lesson and there are no other VNets in the subscription).
az vm deallocate. ③ “A Consumption environment costs nothing when unused”: apps with min_replicas ≥ 1 are billed continuously (despite the free allowance); the load balancer and public IP of a VNet-integrated environment are also billed continuously. ④ “If destroy fails, use az group delete”: it can serve as a last resort, but afterward you must clear state (terraform state rm or delete the state blob), otherwise the next plan will try to refresh resources that no longer exist.destroy order (reverse dependency graph)
Cleanup scope: what Terraform manages and what it does not
Cost estimator + destroy-order animation
Adjust the retention time and optional items to estimate the cost of this lesson's resources (illustrative unit prices, for understanding scale only; actual figures follow the Pricing Calculator); then play the destroy order.
Core commands and flags
| Command | Purpose | Notes |
|---|---|---|
terraform plan -destroy | Preview resources to be deleted | Look carefully before deleting |
terraform destroy | Delete all resources in state | -target Delete only some (emergency) |
az resource list -g rg-tf-lab -o table | Check for leftovers in the resource group | When destroy fails |
az group list --query "[?starts_with(name,'ME_')]" | View the ACA managed resource group | Should disappear after the environment is deleted |
az keyvault list-deleted / az keyvault purge | Soft-deleted Key Vault | Cannot be purged when purge protection is on |
az monitor log-analytics workspace list-deleted-workspaces | Soft-deleted workspace | Automatically restored when recreated with the same name |
az group delete -n RG --yes --no-wait | Last resort: delete the resource group directly | Then clean up state |
az lock delete | Delete the resource lock | Before cleaning up the state account |
resource "azurerm_consumption_budget_resource_group" "lab" {
name = "budget-tf-lab"
resource_group_id = azurerm_resource_group.lab.id
amount = 10 # 10 per month (billing currency)
time_grain = "Monthly"
time_period {
start_date = "2026-11-01T00:00:00Z" # must be the 1st day of a month
}
notification {
enabled = true
threshold = 80
operator = "GreaterThan"
threshold_type = "Forecasted"
contact_emails = ["you@contoso.com"]
}
}
How to verify:az consumption budget list -g rg-tf-lab -o table (some subscription types do not support the consumption API; see the documentation). Common errors:start_date A start date that is not the first of the month will be rejected. Production use: Set budgets per team/environment, combined with owner,cost-center tags for cost allocation; Azure Policy enforces required tags.
Lab 8: destroy + leftover check (about 8 minutes)
cd ~/tf-lab3 && source ~/tf-lab3.env terraform plan -destroy | tail -3 time terraform destroy -auto-approve
Plan: 0 to add, 0 to change, 23 to destroy. azurerm_container_app.myapp: Destroying... [id=/subscriptions/…/containerApps/ca-myapp] azurerm_container_app.redis: Destroying... [id=/subscriptions/…/containerApps/ca-redis] azurerm_container_app.myapp: Destruction complete after 22s … azurerm_container_app_environment.lab: Still destroying... [2m0s elapsed] azurerm_key_vault.lab: Destruction complete after 1m10s … azurerm_resource_group.lab: Destruction complete after 47s Destroy complete! Resources: 23 destroyed.
az group exists -n rg-tf-lab az group exists -n rg-tf-lab-avm az group list --query "[?starts_with(name,'ME_') || name=='NetworkWatcherRG'].name" -o tsv az keyvault list-deleted --query "[?starts_with(name,'kv-tflab')].name" -o tsv az monitor log-analytics workspace list-deleted-workspaces --query "[?starts_with(name,'log-tflab')].name" -o tsv 2>/dev/null terraform state list | wc -l
false false NetworkWatcherRG log-tflab 0
log-tflab Still in soft delete (recreating with the same name within 14 days restores it automatically and incurs no charges). NetworkWatcherRG If it was created in this lesson and the subscription has no other VNets, you can delete az group delete -n NetworkWatcherRG --yes; in enterprise subscriptions it is usually managed by the platform, so do not delete it.
az lock delete -n lock-tfstate -g $STATE_RG --resource $STATE_SA --resource-type Microsoft.Storage/storageAccounts az group delete -n $STATE_RG --yes --no-wait rm -f ~/tf-lab3/*.tfplan ~/tf-lab3/tf.log
~/tf-lab3 The directory can be kept as a code reference (no secrets; state is remote); ~/tf-lab3.env contains only the subscription ID and account name.Case 1: a forgotten lab environment
Problem: The end-of-month bill showed an AKS cluster and Managed Redis that had been running for 3 weeks, and nobody remembered who created them. Approach: Azure Policy requires owner and expires tags; a daily automation script lists expired resource groups, sends notifications, and automatically deletes groups 3 days past expiry; the lab subscription sets budgets and action group alerts. Limitations: Automatic deletion must be preceded by a sufficient notice period and an exemption mechanism.
Case 2: destroy stuck at resource group deletion
Problem:the Resource Group still contains Resources. Cause: Someone added a storage account to the lab resource group in the portal. Approach: After identifying the owner, import or delete it; keep prevent_deletion_if_contains_resources = true, which prevented an accidental deletion of someone else's data. Limitations: Some services automatically create supporting resources in the resource group (such as certain diagnostic or extension resources), which must be identified one by one.
Case 3: purge protection makes recreation fail
Problem: The production template's Key Vault had purge protection enabled; the test environment was destroyed and applied frequently, and the second apply reported a name conflict. Approach: Give test environment names a random suffix; or use recover_soft_deleted_key_vaults = true to let the provider recover the same-name Key Vault. Limitations: Once purge protection is enabled, it cannot be permanently deleted during the soft-delete period; this is part of compliance requirements.
Common errors and fixes
Error: deleting Resource Group "rg-tf-lab": the Resource Group still contains Resources. Terraform is configured to check for Resources within the Resource Group when deleting the Resource Group
Cause: The group contains resources outside state.
az resource list -g rg-tf-lab --query "[].{name:name,type:type}" -o table
Fix: After confirming ownership, delete or import them, then run destroy again.
InUseSubnetCannotBeDeleted … serviceAssociationLinks/legionservicelink or …/managedEnvironments
Cause: After the environment is deleted, it takes time for the platform to release the service association links on the subnet.
Fix: Wait a few minutes and rerun terraform destroy (it continues from the remaining resources).
ScopeLocked: The scope '…/sttfstate…' cannot perform delete operation because following scope(s) are locked
Cause: the CanNotDelete lock added in M2.
Fix: After confirming the deletion is intended, first run az lock delete.
purging Key Vault … Operation "purge" is not allowed because purge protection is enabled
Cause: purge protection is enabled.
Fix: It cannot be purged early; you can only wait for the retention period to end; use a different name next time. Keep the lab environment set to purge_protection_enabled = false.
apply after destroy: Error: retrieving … 404 Not Found (in state, but already deleted manually in Azure)
Cause: The resource was deleted outside Terraform. Normally refresh removes it from state and plans to recreate it; if certain resources are handled abnormally, handle them manually.
Fix:terraform plan -refresh-only Check; if necessary, terraform state rm <address>.
1. Delete only the optional VM-related resources and keep the rest (an emergency approach that does not change code).
terraform destroy -target='azurerm_linux_virtual_machine.vm' -target='azurerm_network_interface.vm' -target='azurerm_public_ip.vm' # Recommended approach: apply -var enable_vm=false (keeps code and state consistent)
2. Use one command to list all resource groups in the subscription with course=terraform-8h tag.
az group list --tag course=terraform-8h --query "[].name" -o tsv
You need to set up a copy of this lesson's environment for each of 20 learners, with a 2-week study period. Design a cost control and cleanup plan.
One resource group per person (name includes the learner ID and a random suffix), with uniform tags course,owner, and expires; each resource group azurerm_consumption_budget_resource_group should have a forecast 80% alert; every night, the pipeline runs terraform destroy for all learners' root modules (or set ACA to min_replicas 0 and delete VM/Redis), and apply as needed in the morning; share one state storage account with one key per person, and learner identities can only access their own container; use Policy to forbid VMs and Managed Redis or restrict them to minimum sizes; when the course ends, uniformly delete the resource groups, purge soft-deleted resources, and delete the state account.
Verified instructional videos
Official documentation
- Container Apps pricing (free allowance) · Container Apps billing details
- terraform destroy
- azurerm features block (deletion behavior)
- Create a budget
Video storyboard script (about 70 seconds)
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided for a video tool to produce it.
Visual: next to the resource list, a pricing dial appears: ACR by the day, ACA by the second, VMs by the hour.
Narration: first understand how each resource is billed. The container registry is billed daily, container apps are billed per second with a free allowance, and VMs are billed by size.
Visual: in the dependency graph, items turn red and disappear from right to left, and finally the resource group disappears.
Narration: terraform destroy deletes in reverse dependency-graph order: apps first, and networking and the resource group last.
Visual: a magnifying glass sweeps over NetworkWatcherRG, the soft-deleted workspace, and the state storage account.
Narration: finally, check for leftovers that Terraform does not manage: Network Watcher, soft-deleted resources, and the state storage that is deleted only after the course ends.
Command cheat sheet
Authentication and subscriptions
az login [--use-device-code] az account set -s "<subscription>" export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) az account get-access-token --resource https://management.azure.com/ --query expiresOn # CI (OIDC) export ARM_USE_OIDC=true ARM_USE_CLI=false ARM_CLIENT_ID=… ARM_TENANT_ID=… # Azure VM (managed identity) export ARM_USE_MSI=true ARM_CLIENT_ID=<uami-client-id>
Resource providers
az provider register -n Microsoft.App --wait az provider show -n Microsoft.App --query registrationState -o tsv az provider list --query "[?registrationState=='NotRegistered'].namespace" -o tsv # provider block (5.x) # resource_provider_registrations = "none" # default # resource_providers_to_register = ["Microsoft.App"]
Remote state (azurerm backend)
terraform init -migrate-state -backend-config=backend.hcl terraform init -reconfigure -backend-config=backend.hcl terraform force-unlock <LOCK_ID> terraform state pull > backup.tfstate az storage blob show --account-name $STATE_SA -c tfstate -n KEY --auth-mode login --query properties.lease az storage blob list --account-name $STATE_SA -c tfstate --auth-mode login --include v -o table
Networking
terraform console <<< 'cidrsubnet("10.30.0.0/16", 7, 0)'
az network vnet subnet list -g rg-tf-lab --vnet-name vnet-tflab \
--query "[].{n:name,p:addressPrefix,d:delegations[0].serviceName}" -o table
az network nsg rule list -g rg-tf-lab --nsg-name nsg-vm --include-default -o tableContainer Apps
curl -s $(terraform output -raw app_url) az containerapp revision list -g rg-tf-lab -n ca-myapp -o table az containerapp logs show -g rg-tf-lab -n ca-myapp --type system --tail 30 az containerapp logs show -g rg-tf-lab -n ca-myapp --type console --tail 30 az containerapp revision restart -g rg-tf-lab -n ca-myapp --revision REV az acr repository show-tags -n $ACR --repository myapp -o table
Identity and secrets
az role assignment list --assignee <principalId> --all -o table az keyvault secret list-versions --vault-name $KV -n redis-password -o table az keyvault list-deleted -o table; az keyvault purge -n KV terraform state pull | grep -c "$PW" # 0 = secret not in state terraform apply -var redis_password_version=2 # rotate
Troubleshooting
TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform apply az monitor activity-log list -g rg-tf-lab --status Failed --offset 1h -o jsonc az vm list-usage -l canadacentral -o table az vm list-skus -l canadacentral --size Standard_B2s -o table terraform plan -generate-config-out=generated.tf # use with import blocks terraform plan -detailed-exitcode # drift detection
Cleanup
terraform plan -destroy terraform destroy -auto-approve az resource list -g rg-tf-lab -o table az group list --query "[?starts_with(name,'ME_') || name=='NetworkWatcherRG'].name" -o tsv az lock delete -n lock-tfstate -g $STATE_RG --resource $STATE_SA --resource-type Microsoft.Storage/storageAccounts az group delete -n rg-tfstate --yes --no-wait
Quick troubleshooting table
| Symptom / error code | What to do first | Common cause → fix |
|---|---|---|
subscription ID could not be determined | env | grep ARM_ | Subscription not set → ARM_SUBSCRIPTION_ID |
Unsupported argument "skip_provider_registration" | Check provider version | Removed in 5.0 → resource_provider_registrations |
MissingSubscriptionRegistration | az provider show | Not registered by default in 5.0 → register RP |
AuthorizationFailed (403) | Read the action/scope in the error | Missing role → least privilege |
AuthorizationPermissionMismatch (state) | Role on the container | Missing Storage Blob Data Contributor |
KeyBasedAuthenticationNotPermitted | backend configuration | Add use_azuread_auth = true |
Error acquiring the state lock | , confirm the lock holder | Concurrent run or leftover → wait / force-unlock |
already exists - … needs to be imported | az resource show | Manually created or last attempt failed → import block |
ForbiddenByRbac (Key Vault) | Data-plane role | Missing Secrets Officer/User or not yet propagated → authorize + time_sleep |
PrincipalNotFound | Was the principal just created? | replication delay → principal_type |
OperationNotAllowed … quota | az vm list-usage | Insufficient quota → change SKU / request |
| revision Unhealthy / upstream connect error | System logs | target_port, probes, image |
no available releases match … < 5.0.0, ~> 5.14 | terraform providers | AVM constrains azurerm 4.x → switch module / split root module |
For the full interactive troubleshooting flow, see Module 7 → Troubleshooting → troubleshooting tree.
Recommended configuration snippet: azurerm 5.x root module skeleton
terraform {
required_version = ">= 1.11"
required_providers {
azurerm = { source = "hashicorp/azurerm", version = "~> 5.14" }
azapi = { source = "Azure/azapi", version = "~> 2.13" }
random = { source = "hashicorp/random", version = "~> 3.7" }
time = { source = "hashicorp/time", version = "~> 0.13" }
}
backend "azurerm" {
use_azuread_auth = true
container_name = "tfstate"
key = "<system>/<env>/<component>.tfstate"
}
}
provider "azurerm" {
resource_provider_registrations = "none"
storage_use_azuread = true
features {
key_vault {
purge_soft_delete_on_destroy = false # production: do not purge on destroy
}
resource_group {
prevent_deletion_if_contains_resources = true
}
}
}
# secrets: ephemeral + write-only
ephemeral "random_password" "db" { length = 32 }
resource "azurerm_key_vault_secret" "db" {
name = "db-password"
key_vault_id = azurerm_key_vault.main.id
value_wo = ephemeral.random_password.db.result
value_wo_version = 1
}
# authorization: explicit principal_type for newly created principals
resource "azurerm_role_assignment" "pull" {
scope = azurerm_container_registry.main.id
role_definition_name = "AcrPull"
principal_id = azurerm_user_assigned_identity.app.principal_id
principal_type = "ServicePrincipal"
}
Capstone lab + final quiz
terraform apply run (local-exec may be used to build the image for the demo); ⑥ after acceptance, run terraform destroy and prove there are no leftovers.Required permissions: Owner of the lab subscription/resource group (or Contributor + RBAC Administrator) + subscription-level RP registration permission. Risk: myapp is open to the public internet (no authentication) and is for demonstration only; destroy it immediately after finishing.
source ~/tf-lab3.env # if rg-tfstate was deleted, rerun bootstrap-state.sh from M0
mkdir -p ~/tf-final && cd ~/tf-final
cp ~/tf-lab3/{versions.tf,providers.tf,backend.tf,main.tf,network.tf,compute.tf,secrets.tf} . 2>/dev/null || echo "Missing files; copy them from the Commands tab of each module"
cp ~/tf-lab3/cloud-init.yaml.tftpl . 2>/dev/null; cp ~/tf-lab3/vm.tf . 2>/dev/null
sed -i 's#lab3/myapp.tfstate#final/myapp.tfstate#' backend.tf
echo "storage_account_name = \"$STATE_SA\"" > backend.hcl
printf 'admin_cidr = "%s/32"\napp_version = "2.0.0"\nredis_password_version = 1\n' "$(curl -s https://api.ipify.org)" > terraform.tfvars
terraform init -backend-config=backend.hcl
terraform validate && terraform fmt -check -recursive
Successfully configured the backend "azurerm"! Terraform has been successfully initialized! Success! The configuration is valid.
If you copied M6's azapi-demo.tf, keep azapi's required_providers in versions.tf. Confirm that myapp's compute.tf already includes M5's secret and REDIS_* environment variable additions.
terraform plan -out=final.tfplan | tail -1
terraform show -json final.tfplan > plan.json
python3 - <<'EOF'
import json
p=json.load(open("plan.json"))
types=sorted({r["type"] for r in p.get("resource_changes",[])})
print(len(p["resource_changes"]),"changes;", ", ".join(types))
kv=[r for r in p["resource_changes"] if r["type"]=="azurerm_key_vault_secret"][0]
print("value in plan:", kv["change"]["after"].get("value"), "| value_wo in plan:", kv["change"]["after"].get("value_wo"))
EOF
Plan: 22 to add, 0 to change, 0 to destroy. 22 changes; azurerm_container_app, azurerm_container_app_environment, azurerm_container_registry, azurerm_key_vault, azurerm_key_vault_secret, azurerm_log_analytics_workspace, azurerm_network_security_group, azurerm_resource_group, azurerm_role_assignment, azurerm_subnet, azurerm_subnet_network_security_group_association, azurerm_user_assigned_identity, azurerm_virtual_network, random_string, terraform_data, time_sleep value in plan: None | value_wo in plan: None
time terraform apply final.tfplan terraform output
Apply complete! Resources: 22 added, 0 changed, 0 destroyed. acr_name = "acrtflabp7m2d" app_url = "https://ca-myapp.bluefield-9e8d7c6b.canadacentral.azurecontainerapps.io" real 9m41s
If you hit 403 / pull failures at the Key Vault secret or ca-redis, RBAC has not yet propagated: rerun terraform apply (M7); if it keeps happening, change time_sleep.rbac to 180s.
URL=$(terraform output -raw app_url)
for i in 1 2 3; do curl -s $URL; done
curl -s -o /dev/null -w "healthz=%{http_code}\n" $URL/healthz
KV=$(terraform state show azurerm_key_vault.lab | awk -F'"' '/^ *name /{print $2; exit}')
PW=$(az keyvault secret show --vault-name $KV -n redis-password --query value -o tsv)
echo "secret-in-state: $(terraform state pull | grep -c "$PW")"
az storage account show -n $STATE_SA --query allowSharedKeyAccess
az acr show -n $(terraform output -raw acr_name) --query adminUserEnabled
az containerapp show -g rg-tf-lab -n ca-redis --query "properties.configuration.ingress.{external:external,transport:transport}" -o tsv
[2.0.0] Hello from ca-myapp--0000001-…, hits=1 [2.0.0] Hello from ca-myapp--0000001-…, hits=2 [2.0.0] Hello from ca-myapp--0000001-…, hits=3 healthz=200 secret-in-state: 0 false false False Tcp
terraform plan -detailed-exitcode >/dev/null; echo "exit=$? (0 = no drift)" az containerapp update -g rg-tf-lab -n ca-myapp --max-replicas 5 -o none # simulate a manual change in the portal terraform plan | grep -E "max_replicas|Plan:" terraform apply -auto-approve >/dev/null && echo "Drift corrected"
exit=0 (0 = no drift)
~ max_replicas = 5 -> 3
Plan: 0 to add, 1 to change, 0 to destroy.
Drift correctedsed -i 's/redis_password_version = 1/redis_password_version = 2/' terraform.tfvars terraform apply -auto-approve | grep -E "value_wo_version|Apply complete" for app in ca-redis ca-myapp; do az containerapp revision restart -g rg-tf-lab -n $app --revision $(az containerapp show -g rg-tf-lab -n $app --query properties.latestRevisionName -o tsv) -o none; done sleep 40; curl -s $URL
terraform destroy -auto-approve | tail -1 az group exists -n rg-tf-lab az keyvault list-deleted --query "[?name=='$KV'].name" -o tsv terraform state list | wc -l
Destroy complete! Resources: 22 destroyed. false 0
After the whole course ends, delete per M8 rg-tfstate (delete the lock first).
Open-ended self-check (answer first yourself, then expand the reference answer)
1. When upgrading from azurerm 4.x to 5.x, what three things should you at least check at the provider block level?
①skip_provider_registration removed,resource_provider_registrations default changes to none, so confirm RPs are registered or explicitly listed; ②enhanced_validation moved into features block and disabled by default,ARM_PROVIDER_ENHANCED_VALIDATION removed; ③ the subscription ID must be determinable (since 4.0). Also check each resource's breaking changes in the upgrade guide (for example, Key Vault rbac_authorization_enabled required, ACA environment logs_destination, removed resources).
2. How does the azurerm backend implement locking? How do you safely handle a leftover lock?
It acquires an infinite-duration lease on the state blob and writes the lock information into metadata; other processes that try to acquire the lease get a 409 and show Lock Info. For a leftover lock, first confirm that the process/pipeline identified by Who has actually ended, then run terraform force-unlock <ID>; in CI, use -lock-timeout to queue.
3. Describe one azurerm_container_app creation's full request sequence on ARM.
core calls ApplyResourceChange → provider GET the resource (continue only on 404; 200 reports already exists) → PUT (ARM authentication, RBAC, Policy, forwarding to the RP) → 201/202 + Azure-AsyncOperation/Location + Retry-After → poll until Succeeded/Failed → GET the resource to obtain computed attributes → return NewState → core writes state (blob, with lease).
4. Why use a user-assigned identity rather than a system-assigned identity to pull ACR images?
A user-assigned identity exists independently, so AcrPull authorization can be completed before the app is created (and allowed to propagate), and the first pull already has permission when the app is created. A system-assigned identity is generated only when the app is created, so authorization can only be done afterward, and the first revision often fails to pull. A user-assigned identity can also be shared by myapp and redis.
5. What problem does each of sensitive variables, ephemeral resources, and write-only arguments solve?
sensitive: only masks the value in CLI output; the value is still in plan/state. ephemeral: the value exists only in memory during this run and is not written to plan/state (Terraform 1.10+). write-only: the resource argument is sent only to the provider and not stored in state (1.11+); it can accept ephemeral values, with updates triggered via *_wo_version .
6. When should you use azapi instead of azurerm or AVM? Give two examples.
New resources or preview APIs that azurerm does not yet support (azapi_resource); a patch when an azurerm resource lacks a certain property (azapi_update_resource); reading properties that azurerm does not export (data azapi_resource); when an AVM module cannot be used because of an azurerm version constraint conflict, choose a pure-azapi module or write azapi directly.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Terraform CLI | Latest v1.17.2 (2026-11-11); Terraform Policy GA since 1.17.0,-minimal-refresh; ephemeral resources since 1.10, write-only arguments since 1.11 | terraform releases · Ephemeral resources |
| azurerm version | Latest 5.14.0 (2026-11-13); 5.0.0 released 2026-07-28; last 4.x version 4.81.0 (2026-07-14) | registry: hashicorp/azurerm(v2 API version list) |
| azurerm 4.0 changes | subscription ID must be specified (subscription_id / ARM_SUBSCRIPTION_ID); added resource_provider_registrations (core/extended/all/none/legacy) and resource_providers_to_register,skip_provider_registration deprecated | 4.0 Upgrade Guide |
| azurerm 5.0 changes | resource_provider_registrations Default none; skip_provider_registration removed; enhanced_validation moved into features and disabled by default; added preflight_enabled; removed ARM_PROVIDER_ENHANCED_VALIDATION; Key Vault enable_rbac_authorization removed,rbac_authorization_enabled required; ACA environment logs_destination no longer computed; storage container storage_account_name removed (use storage_account_id); subnet service_endpoints changed to service_endpoint block; azurerm_redis_enterprise_cluster/database and other resources removed | 5.0 Upgrade Guide(GitHub website/docs/guides/5.0-upgrade-guide.html.markdown) |
| azurerm authentication and features | use_cli default true; use_oidc/use_msi/use_aks_workload_identity; storage_use_azuread; features: persist_id_on_create_before_polling_for_completion (default false), key_vault purge/recover (default true),log_analytics_workspace.permanently_delete_on_destroy (default false),resource_group.prevent_deletion_if_contains_resources | provider documentation · features block |
| resource arguments | azurerm_container_app: registry.identity (must be declared in the identity block, and mutually exclusive with username/password),secret.key_vault_secret_id + identity; azurerm_key_vault_secret: value_wo,value_wo_version,versionless_id; ephemeral azurerm_key_vault_secret; azurerm_role_assignment.principal_type; azurerm_managed_redis | container_app · key_vault_secret · role_assignment |
| azurerm backend | Entra ID (CLI/OIDC/MSI) + use_azuread_auth recommended; required role Storage Blob Data Contributor; access keys/SAS are only for backward compatibility; lookup_blob_endpoint requires Reader; native locking | Backend Type: azurerm (v1.17.x) |
| random / time provider | random 3.9.1 (2026-09-11), ephemeral random_password since 3.7.0 (2025-02-25); time 0.14.2 (2026-09-11) | random CHANGELOG · registry |
| azapi | 2.13.0 (2026-09-28); azapi_resource of body is a dynamic HCL object, supporting response_export_values,schema_validation_enabled (default true),sensitive_body (write-only),retry | azapi_resource |
| AVM modules | avm-res-network-virtualnetwork 0.23.0 (azapi ~> 2.12); avm-res-keyvault-vault 0.13.1 (azurerm >= 4.81, < 5.0); avm-res-containerregistry-registry 0.9.0 (< 5.0.0); avm-res-managedidentity-userassignedidentity 0.6.0 (< 5.0.0); avm-res-app-containerapp 0.9.0, avm-res-app-managedenvironment 0.6.0, avm-res-storage-storageaccount 0.11.0 (azapi) | registry.terraform.io module API (/v1/modules/Azure/<name>/azurerm) · AVM site |
| Container Apps networking | workload profile environment: subnet minimum /27, delegated to Microsoft.App/environments, 12 fixed infrastructure addresses; Consumption-only: /23, must not be delegated; reserved address ranges; the managed resource groups (ME_/MC_) of a VNet environment are billed extra; external TCP ingress requires a VNet | Custom virtual networks(updated 2026-05-19) · Ingress overview(2026-10-22) |
| Sample apps and lab scenarios | myapp (Flask + Redis, port 5000, /healthz), internal TCP Redis + Key Vault reference, corresponding to Docker lesson 3 | Docker Hour 3 |
Video verification notes
The following videos were verified through the YouTube oEmbed endpoint (2026-11-15) for their titles, channels and video IDs: freeCodeCamp.org “Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners” (V53AHWun17s); TechWorld with Nana “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE); Fireship “Terraform in 100 Seconds” (tomUWcQ0P3k); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); KodeKloud “Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide!” (YcJ9IeukJL8); HashiCorp, an IBM Company “Introduction to HashiCorp Terraform with Armon Dadgar” (h970ZBgKINg); John Savill's Technical Training “Microsoft Azure Managed Identity Deep Dive” (rC1TV0_sIrM), “Azure Verified Modules Overview” (3FeIFHaJOtg); Ned in the Cloud “Introducing Azure Verified Modules for Terraform” (6OeRByC-sBs); Code To Cloud “Getting Started With: Azure Verified Modules” (y1lOKQOapTw); ITOpsTalk “Building Secure, Well‑Architected Azure Workloads with Azure Verified Modules and GitHub Copilot” (QBqRAMVTmwE). The oEmbed endpoint does not return durations or publish dates, so no durations are listed on the cards. No verified dedicated videos were found for the azurerm backend, ephemeral/write-only, Container Apps + Terraform, or troubleshooting and cost control in the cloud, so storyboard scripts are provided instead. All videos are in English, and most were recorded before azurerm 5.0.
Voice narration notes
The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) reads the narration script aloud in real time, with English terms pronounced in en-US. The result depends on the voices installed on the system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; if you need offline audio, hand the narration script to a TTS service such as Azure AI Speech to generate it.
Known limitations
- Commands in this courseware Not run against a real subscription; the subscription, tenant and object IDs, resource name suffixes, FQDNs, IPs, version IDs, durations and resource counts in “Expected output” are sample values, and your own environment is authoritative.
- The sidebar label “azurerm 4.x” reflects the original plan; the body has been written against azurerm 5.14.0 as verified on 2026-11-15. The provider docs reference the GitHub main branch (the latest docs after release), so some fields may be earlier or later than the version you have installed; refer to the registry docs for your version.
- Internal details of the backend lock (the lease never expires, the metadata key name
terraformlockid, workspace key nameenv:suffix) are based on Terraform source behavior; the official docs only describe “native locking”; the ARM api-version is set by the provider's built-in SDK, and the version numbers in the examples are illustrative only. - Error message text changes with Terraform, provider and Azure versions; this lesson shows typical forms.
- Costs are order-of-magnitude estimates, and unit prices in the animations are illustrative; the Container Apps free allowance and per-service unit prices are defined on the Azure pricing page.
- RBAC propagation time is uncertain,
time_sleepthe 90 seconds is an empirical value; the propagation delay in the animation is illustrative. - The demo Redis (an internal TCP app in ACA) has no persistence and no high availability, and is for teaching only;
terraform_data+local-execbuilding the image is only for single-person lab convenience; in production, image building belongs to CI (lesson 5). - AVM module versions and provider constraints change very quickly, so reconfirm them in the registry before use.