Terraform Hour 3: Moving to the Cloud Platform (Azure)

Use the HCL, state and modules you practiced locally in lessons 1 and 2 on a real cloud: use Terraform to deliver the complete myapp stack on Azure (VNet + ACR + Container Apps + Key Vault + Redis), then destroy everything with one final command
Terraform v1.17.2azurerm 5.14.0azapi 2.13.0AVM modulesVerified against official docs · 2026-11
Overall learning goals
  • 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_id a 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 privilege Storage Blob Data Contributor.
  • Use for_each to 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

#TimeModuleCore contentAnimation / interactionLab (Azure subscription · canadacentral)
0Pre-classWarm-up and Azure setupaz CLI login, subscription and permission checks, registering resource providers, preparing the myapp image source, bootstrapping the state storage accountEnvironment self-check listbootstrap-state.sh
100–06azurerm provider and authenticationFour 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 simulatorRun the first plan with CLI authentication
206–13azurerm remote backendStorage account + Entra ID authentication, blob lease locks, versioning/soft delete, state access control,-migrate-stateTwo people applying at the same time: lease lock animationMigrate local state to Azure Blob
313–21Networking: VNet, subnets, NSGCIDR planning,for_each generating subnets, subnet delegation, NSG rules and associations,cidrsubnet()count vs for_each subnet deletion comparisonVNet + 3 subnets + NSG
421–30Compute: VMs and Container AppsVM + cloud-init, ACR, Container Apps environment (VNet integration), user-assigned identity + AcrPull, ingress/probes/scalingCore animation: Terraform → provider gRPC → ARM REST PUT/polling → write stateACR + ACA deploy myapp
530–37Identity and secretsmanaged 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?" comparatorRedis password never lands in state
637–45AVM and azapiAVM naming and conventions, version constraint conflicts, azapi_resource / azapi_update_resource / data azapi_resource, when to use azapiazurerm / azapi / AVM selection wizardUse AVM to build a VNet + azapi to read ACA properties
745–53Troubleshooting on Azure in practiceAuthentication failures, 403, already exists → import, quota, MissingSubscriptionRegistration, PrincipalNotFound, ForbiddenByRbacRole assignment propagation race simulation + Interactive troubleshooting treeDeliberately cause 4 faults and fix them
853–60Cost, cleanup and self-checkBilling points, tags and budgets,terraform destroy order, soft-delete leftovers, orphaned resource checksCost estimator + destroy order animationdestroy + leftover check
—Post-classCheat sheet · Capstone labOne apply delivers the full myapp stack; destroy after verificationFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / resourcesLab
azurerm authentication and subscription selection✓✓····✓·az login,ARM_* environment variablesM1
resource provider registration✓··✓··✓·resource_providers_to_register,az provider registerM0 / M7
remote state and locking·✓····✓✓backend "azurerm",force-unlockM2
networking and for_each··✓✓·✓··azurerm_subnet,cidrsubnet()M3
VM and cloud-init··✓✓··✓✓azurerm_linux_virtual_machine,custom_dataM4 (optional)
Container Apps + ACR passwordless pull···✓✓✓✓·azurerm_container_app registry.identityM4
managed identity and role assignments✓··✓✓·✓·azurerm_role_assignment,principal_typeM5
Key Vault and keeping secrets out of state····✓·✓✓ephemeral,value_woM5
AVM / azapi selection·····✓✓·module "avm-res-…",azapi_resourceM6
cloud troubleshooting (import, quota, 403)✓✓·✓✓·✓·import block,TF_LOG,az vm list-usageM7
Cost control and full cleanup···✓···✓terraform destroy,az keyvault purgeM8

What this lesson does not cover (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
AWS (VPC, ECS Fargate, IAM, S3 backend use_lockfile)The next lesson covers the same myapp for comparisonLesson 4: Moving to the Cloud Platform (AWS)
Full setup of GitHub Actions pipelines, federated credentials, plan review, PolicyThis lesson only covers the OIDC principles and provider configuration in M1Lesson 5: Automated operations
Multi-environment/multi-region architecture, Landing Zones, Hub-Spoke, full private endpoint coverageBeyond 1 hourLesson 6: Architecture practice;AVM official site
AKS clusters and the Kubernetes providerbelongs to the K8s trackKubernetes 8 + 1-hour lessons
Container Apps operational details such as revisions, traffic splitting and KQL logsThe Docker lesson already covered it with az CLIDocker Hour 3 (Azure)
OpenTofu state encryptionTerraform itself does not provide client-side state encryption; it is covered in the advanced topicsLesson 7

How to use this course material

10 pages per module
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.
Learning progress
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).
Chinese voice
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.
Cost note This lesson creates real resources in your subscription: ACR Basic, a Container Apps environment (workload profile, Consumption billing), Log Analytics, Key Vault and a storage account; optionally a Linux VM and Azure Managed Redis. If you follow this lesson's pace and destroy everything the same day, the cost is usually a few dollars or less (Container Apps Consumption has a monthly free allowance; ACR Basic is billed daily; VMs and Managed Redis are billed hourly, so delete optional steps as soon as you finish them). For exact prices, refer to the Azure Pricing Calculator. Be sure to runModule 8 cleanup steps.
Version notes The sidebar says "azurerm 4.x", which was the baseline this lesson was originally planned around. When verified on 2026-11-15,azurerm 5.0.0 had been released (2026-07-28), and the latest is 5.14.0 (2026-11-13); the last 4.x release is 4.81.0 (2026-07-14). So this lesson's code is pinned to ~> 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)

Sign-in and subscription, permission self-check, resource provider registration, preparing the myapp source, and bootstrapping a storage account for state with the az CLI
Pre-class ≈ 12 minTerraform 1.17.2 · az CLI
Prerequisites
  • CompletedLesson 1andLesson 2: you can write variable/output/locals/for_each, have used kreuzwerker/docker provider to deploy myapp + Redis locally, and understand state, locks, modules and moved/import blocks.
  • 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 through REDIS_HOST/PORT/PASSWORD/SSL to configure Redis).

Connection from the previous lesson

What you did in lesson 2The Azure equivalent in this lesson
kreuzwerker/docker provider running a container locallyhashicorp/azurerm Calling the Azure Resource Manager (ARM) REST API
MinIO simulating S3 for remote stateAzure storage account blob for remote state (native lease locking)
docker_network + container name accessVNet + 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 containersimport 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
Why check This lesson creates 4 role assignments (AcrPull, Key Vault Secrets User, Key Vault Secrets Officer, Storage Blob Data Contributor). With only Contributor,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).

Environment self-check list

Module 1 · azurerm provider and authentication

00:00 – 06:00 · the provider first obtains an Entra ID access token before it can call ARM on your behalf; where the token comes from determines security and portability
6 minazurerm 5.14.04.0: subscription_id required · 5.0: RP registration default none★★★★★
Learning goals
  • Write a terraform + provider block that meets azurerm 5.x requirements: version constraints features {},subscription_id and 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.
Prerequisites: Lesson 1's 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_id to be given explicitly; 5.0 changes the resource provider registration default to none, removes skip_provider_registration, and moves enhanced_validation into the features block and disables it by default. Copying configuration from old blogs will cause direct errors.

How: how the provider gets a token

MethodSwitch / environment variableToken acquisition mechanismApplicable scenarios
Azure CLIuse_cli (default true) / ARM_USE_CLIprovider 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 identityLocal development, classroom labs
Service principal + client secret/certificateARM_CLIENT_ID,ARM_TENANT_ID,ARM_CLIENT_SECRET or ARM_CLIENT_CERTIFICATE_PATHOAuth 2.0 client credentials: POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/tokenLegacy 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_IDrequests 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_IDthe 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)

VersionChangeWhat 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.0Added resource_provider_registrations (core / extended / all / legacy / none) and resource_providers_to_register; skip_provider_registration Deprecated; in 4.x the default is legacychoose 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 removedregister with az in advance, or resource_providers_to_register = [...]; to keep the old behavior, write "legacy"
5.0enhanced_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 removedto 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

azurermAWS provider (Lesson 4)az CLI / Bicep
Local credentialsAzure CLI sessionAWS CLI profile / SSOSame az login session
CI passwordlessOIDC → Entra ID federated credentialOIDC → IAM OIDC provider + AssumeRoleWithWebIdentityazure/login Action (OIDC)
Target scopesubscription (subscription_id), use aliases for multiple subscriptionsaccount + region (region)az account set / deployment scope
API prerequisite switchesResource provider registrationNone (the service default is available; some require enabling)Same as azurerm; some CLI commands register automatically
Common misconceptions① 'Writing 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

Laptop: az loginuse_cli (default true) GitHub Actionsuse_oidc · short-lived JWT Azure VM runneruse_msi · IMDS 169.254.169.254 Service principal + secret/certificateARM_CLIENT_SECRET (not recommended) Microsoft Entra ID/oauth2/v2.0/tokenscope: management.azure.com Bearer terraform-provider-azurerm subscription_id / ARM_SUBSCRIPTION_ID RP registration: none (5.0 default) / list features {} behavior switch PUT/GET management.azure.com/subscriptions/{id}/…?api-version= Tokens are scoped by audience: management plane management.azure.com; Key Vault data plane vault.azure.net; storage storage.azure.com
Figure 1-1: regardless of where the identity comes from, the provider ultimately holds an Entra ID access token to call ARM

Flow diagram: GitHub Actions OIDC token exchange

① runner requests an ID tokenpermissions: id-token: write ② GitHub OIDC issues a JWTiss=token.actions.githubusercontent.comsub=repo:org/app:environment:prod ③ provider sends the assertionclient_assertion=JWTaud=api://AzureADTokenExchange ④ Entra ID validatesfederated credential issuer+subjectmatch → issues access token ⑤ access token valid for about 1 hourno long-lived secret to leak A subject mismatch reports errors like AADSTS700213 / AADSTS70021 (detailed setup in Lesson 5)
Figure 1-2: OIDC turns "store a key" into "trust one issuer + one exact subject"

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.

First select a runtime environment.
$ terraform plan

Core commands and parameters

Command / configPurposeKey parameters / notes
az login / az account set -sEstablish a CLI session, select a subscription--use-device-code (no browser); --tenant
export ARM_SUBSCRIPTION_ID=…tells the provider the target subscriptionSince 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 tokenFor troubleshooting; the output contains expiresOn
az ad sp create-for-rbacCreate a service principal (demo; prefer OIDC in CI)--role,--scopes; it outputs a secret, so protect it
az ad app federated-credential createAdd an OIDC federated credential to an app registrationissuer,subject,audiences
terraform providers / terraform versionCheck the required and installed provider versionsUse with .terraform.lock.hcl
TF_LOG=DEBUG terraform planto inspect authentication details and HTTP requestsLogs 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)

Write versions.tf and providers.tf (contents on the "Commands" page), then add a resource group and a random suffix:
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
  }
}
Initialize and view the provider
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.

First deliberately leave the subscription unset to see the error introduced in 4.0
(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.

apply: create the resource group
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"
}
Look at the requests the provider actually sends (only look at methods and URLs; do not share the full log)
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.

Keep the resource group: the next module will migrate this state to a remote backend, so do not destroy it yet.

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.

Command-line tasks
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
    }
  }
}
Scenario analysis
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

▶
Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners — freeCodeCamp.org
English · complete introductory course, from az login and the azurerm provider to VNet/VM (recorded earlier; for azurerm 4.0/5.0 changes, this lesson takes precedence)
▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · quick review of the relationship between provider, state and plan

Official docs

Video storyboard (about 90 seconds)

This course material cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or achieve a score of ≥ 70% in the quiz

Module 2 · azurerm remote backend

06:00 – 13:00 · put state in a storage account: Entra ID authentication, blob lease locks, version rollback; anyone who can read the state can read the secrets inside it
7 minbackend "azurerm" · Terraform 1.17use_azuread_auth★★★★★
Learning goals
  • 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-state to migrate the module 1 local state to Azure.
Prerequisites: Lesson 2's backend, locks and -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)

Methodbackend parameterRequired permissionRecommendation
Entra ID + Azure CLIuse_cli = true,use_azuread_auth = truecontainer on Storage Blob Data Contributorlocal ✓
Entra ID + OIDCuse_oidc = true,use_azuread_auth = true,client_id,tenant_idsame as aboveCI ✓✓
Entra ID + managed identityuse_msi = true,use_azuread_auth = true (user-assigned, then give client_id)same as aboveAzure self-hosted runner ✓✓
access key lookupgiven resource_group_name and not set use_azuread_authReader + Storage Account Key Operator Service Role✗ legacy
access key / SASaccess_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

  1. When plan/apply starts, the backend sends PUT …/tfstate/<key>?comp=lease to the state blob, with request header x-ms-lease-action: acquire, to get an indefinite lease, obtaining x-ms-lease-id; if the blob does not exist, it first creates an empty blob.
  2. Writes the lock information (ID, operation, who, version, time) as JSON into the blob's metadata (terraformlockid).
  3. 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.
  4. When writing state, it overwrites the blob with the lease ID; after finishing, x-ms-lease-action: release releases it. If the process is force-killed, the lease does not expire automatically (it is indefinite), so you need terraform 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
Lockingblob lease (native)use_lockfile = true S3 native conditional writes (DynamoDB locking is deprecated)Platform-managed
AuthenticationEntra ID (CLI/OIDC/MSI)IAM (profile/OIDC role)platform token; dynamic credentials to access the cloud
Historyblob versioningS3 versioningbuilt-in state version history
Encryption at reststorage server-side encryption (Microsoft-managed keys by default; CMK optional)SSE-S3 / SSE-KMSPlatform encryption
Common misconceptions① 'The storage account is encrypted, so state is safe': server-side encryption only protects against physical media leaks; any identity with Blob Data Reader permission can read the plaintext state. Terraform itself does no client-side encryption (OpenTofu provides state encryption, see Lesson 7). ② 'Giving CI read-only permission lets it plan': plan acquires a lock by default (it writes a lease), so a read-only identity needs -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

Engineer's laptopuse_cli + use_azuread_auth GitHub Actionsuse_oidc + use_azuread_auth script holding an access key403: shared key disabled ✗ Entra ID RBACStorage Blob DataContributor @ containerprod container granted only toprod pipeline identityAudit: Entra sign-in logs rg-tfstate / sttfstate21987 (ZRS) allowSharedKeyAccess=false · TLS1.2 · CanNotDelete lock tfstate container lab3/myapp.tfstate · lease: locked lab3/myapp.tfstate env:dev (workspace) Versioningeach write creates a versioncan roll back soft delete for 14 daysblob + containerprotects against accidental deletion
Figure 2-1: only Entra ID identities can access it; versioning and soft delete act as a safety net

Sequence diagram: backend and Blob service interaction during one apply

terraform (backend) Blob service (data plane) PUT ?comp=lease x-ms-lease-action: acquire duration -1 201 Created x-ms-lease-id: 3f2a… PUT ?comp=metadata x-ms-meta-terraformlockid=… (lock info) GET blob → read current state … plan / apply calls ARM … PUT blob (with x-ms-lease-id) → new state version PUT ?comp=lease x-ms-lease-action: release another process tries to acquire during this time → 409 LeaseAlreadyPresent → "Error acquiring the state lock"
Figure 2-2: lock = lease + lock information in metadata (request headers are the real Blob REST API names; metadata key names follow the source code)

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.

Alice (laptop)
idle
lab3/myapp.tfstate
lease: available · version 7
Bob (CI pipeline)
idle
Ready.
$ terraform apply

Core commands and parameters

CommandPurposeKey parameters / notes
terraform init -migrate-statecopy existing state to the new backend when the backend changesprompts for confirmation; -force-copy skip confirmation (CI)
terraform init -reconfigurere-initialize, ignoring the old backend configuration (no migration)use when switching to a backend that already has state
terraform init -backend-config=FILEpartial configuration: put environment-specific values in a filecan be used multiple times; or also -backend-config="key=value"
terraform force-unlock LOCK_IDrelease a stale lockfirst confirm the lock-holding process has ended; -force skip confirmation
terraform state pull > backup.tfstatedownload the current state (backup / troubleshooting)the output contains sensitive values; be careful where it is saved
az storage blob list --include v --auth-mode loginlist the state's version history--prefix lab3/
az storage blob show … --query properties.leaseview lease statusstatus/state/duration
az lock create --lock-type CanNotDeleteadd 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)

Write backend.tf and backend.hcl, then migrate state (contents on the "Commands" page)
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
Practice a lock conflict: in terminal A, run an apply that waits for confirmation (holding the lock), then run plan in terminal B.
# 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.

Practice a stale lock and force-unlock
# 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!
Rollback practice: view and restore the previous state version
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.

Protect the state storage account
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).

Command-line tasks
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(@)"
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · the sections on remote backends and state locking can serve as supplementary material (uses AWS as the example; the principles are the same)
Note No verified video specifically covering the azurerm backend with Entra ID authentication was found.

Official docs

Video storyboard (about 80 seconds)

This course material cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–65s
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.
Shot 4 · 65–80s
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.
or score ≥ 70% on the quiz

Module 3 · Networking: VNets, subnets, NSGs

13:00 – 21:00 · Plan the address space first, then use for_each to turn the subnet list into resources; delegation and sizing of the Container Apps subnet are the first hurdle
8 minazurerm_virtual_network · azurerm_subnet · NSGACA subnet: delegation + minimum /27★★★★☆
Learning objectives
  • 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 why count removing 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.
Prerequisites: Lesson 1's 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:

SubnetCIDRPurposeSpecial requirements
snet-aca10.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-vm10.30.2.0/24 = cidrsubnet(…, 8, 2)Linux VM (optional in M4)Attach NSG: SSH allowed only from your public IP
snet-pe10.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/24 ranges, and workload profile environments also reserve 100.100.0.0/17 and several other ranges. This lesson chooses 10.30.0.0/16 to 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
ProsCan be referenced individually, associated with NSGs/route tables, and works naturally with for_eachOne PUT creates the VNet and subnets; since 4.0, inline blocks support more options such as delegation and route tables
RisksNoneMixing 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

AzureAWS (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 delegationNo direct equivalent (the service brings its own ENI)—
Common misconceptions① “A /28 is enough for an ACA subnet” — workload profile minimum is /27, Consumption-only minimum is /23, and it cannot be expanded later; for production, start at /23. ② “Applying a strict NSG to the ACA subnet makes it safer” — ACA has outbound dependencies (such as MCR, Entra ID, and monitoring endpoints); an overly strict NSG/UDR causes environment creation or image pulls to fail, so allow them as described in the official “Protect with NSG” docs. ③ “Add the VNet address space later” — you can add address spaces, but existing subnets cannot be changed freely, and if they overlap with a peered network you must rebuild.

Topology diagram: vnet-tflab

vnet-tflab · 10.30.0.0/16 · canadacentral snet-aca · 10.30.0.0/23delegation: Microsoft.App/environments cae-tflab (workload profile)12 infrastructure addresses + replicasConsumption: about 1 IP per 10 replicas myappExternal HTTP redisInternal TCP 6379 snet-vm · 10.30.2.0/24NSG nsg-vm vm-tflab (optional)cloud-init: docker + myapp 110 Allow TCP 22 from your IP/32120 Allow TCP 80 from your IP/3265500 DenyAllInBound (default) snet-pe · 10.30.3.0/24NSG nsg-peReserved: Key Vault / ACR /Redis private endpoint(Lesson 6 architecture practice) 10.30.4.0 – 10.30.255.255 unassigned
Figure 3-1 Address plan: /23 for ACA, /24 for the VM and private endpoints, leaving room to grow

Data flow: how one map becomes multiple resources

local.subnets (map) aca = { newbits 7, netnum 0,delegate "Microsoft.App/…" } vm = { newbits 8, netnum 2, nsg = true } pe = { newbits 8, netnum 3, nsg = true } for_each azurerm_subnet.this[each.key] ["aca"] 10.30.0.0/23 + delegation block["vm"] 10.30.2.0/24["pe"] 10.30.3.0/24dynamic "delegation" is generated only when a value is set Filter nsg=true NSG + associationazurerm_network_security_group.this["vm"], .this["pe"]azurerm_subnet_network_security_group_association.this["vm"/"pe"]Rules come from local.nsg_rules (dynamic)
Figure 3-2 The keys (aca/vm/pe) are part of the resource address; adding or removing one does not affect the others

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.

count = length(var.subnets)
for_each = var.subnets (map)
Click any subnet button above to delete it.
$ terraform plan

Core commands and parameters

Command / functionPurposeNotes
cidrsubnet(prefix, newbits, netnum)Derive subnets from a prefixcidrsubnet("10.30.0.0/16", 8, 2) → 10.30.2.0/24
terraform consoleValidate expressions interactivelyValidate 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 listVerify actual subnets and delegation--query "[].{n:name,p:addressPrefix,d:delegations[0].serviceName}"
az network nsg rule listList NSG rules (including default rules)--include-default
az network watcher test-ip-flowCheck whether a 5-tuple is allowed by the NSGRequires 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)

Get your public IP and write it to tfvars
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"
Write network.tf (see the “Commands” tab), run plan, and check the addresses
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 created
Apply and verify with az
terraform 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
Experience for_each stability: add 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.
Keep resources: leave the network in place for M4. The VNet, subnets, and NSGs themselves are free.

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.

Command-line tasks
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 table
Scenario analysis
The 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

▶
Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners — freeCodeCamp.org
English · the VNet, subnet, NSG, association, and for_each sections correspond to this module

Official documentation

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
or score ≥ 70% on the quiz

Module 4 · Compute: VM (cloud-init) and Container Apps

21:00 – 30:00 · The same HCL delivers IaaS and serverless containers; see what the provider and ARM do behind a single apply: PUT / polling / GET
9 minazurerm_container_app · azurerm_linux_virtual_machineCore animation of this lesson★★★★★
Learning objectives
  • Explain Terraform → provider (gRPC ApplyResourceChange) → ARM REST (existence-check GET → PUT → polling Azure-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 why custom_data some changes cause recreation.
  • Know the changes azurerm 5.0 made to Container Apps environments: logs_destination no longer computed automatically; you must set "log-analytics" to link a workspace.
Prerequisites: ACR/ACA concepts from Docker Lesson 3; the dependency graph from Lesson 1. Importance:★★★★★

What: resources delivered by this module

ResourceTerraform typeKey points
Log Analytics workspaceazurerm_log_analytics_workspacePerGB2018, 30-day retention; ACA app logs are written here
Container registryazurerm_container_registryBasic,admin_enabled = false (no admin account); the name must be globally unique, 5–50 alphanumeric characters
User-assigned managed identityazurerm_user_assigned_identitylifecycle 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 AcrPullazurerm_role_assignmentscope = ACR,principal_type = "ServicePrincipal"
Container Apps environmentazurerm_container_app_environmentinfrastructure_subnet_id = snet-aca; workload_profile Consumption; since 5.0 requires logs_destination = "log-analytics"
myapp appazurerm_container_appregistry { server, identity }; ingress external,target_port = 5000; startup/liveness/readiness probes /healthz
Linux VM (optional)azurerm_linux_virtual_machine + NIC + public IPUbuntu 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)

  1. core walks the dependency graph: when azurerm_container_app.myapp all its dependencies (environment, identity, role assignment, image build) are complete, core calls the provider's ApplyResourceChange, passing prior state (null) and planned state.
  2. Existence check: before creating, azurerm first GET the 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.
  3. 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 (requires Microsoft.App/containerApps/write, and referencing a managed identity also requires Microsoft.ManagedIdentity/userAssignedIdentities/assign/action),Azure Policy evaluation, then forwards the request to the Microsoft.App resource provider.
  4. Long-running operation (LRO): the resource provider returns 201 Created/200 or 202 Accepted, with Azure-AsyncOperation or Location header (and Retry-After). The provider polls at the Retry-After interval GET this operation URL until status is Succeeded/Failed/Canceled; meanwhile the CLI shows Still creating... [20s elapsed].
  5. Final read: on success the provider then GET reads 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.
  6. 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-initAzure Container Apps
When: VM or Container AppsBest forFull OS control, special kernels/drivers, legacy software, Ansible management (Ansible Lesson 3)
HTTP/TCP microservices, event-driven jobs, need to scale to zeroOperationsPatching, monitoring agents, and scaling are all on you (or VMSS)
The platform handles nodes, TLS, scaling (KEDA), and revisionsCostBilled hourly by VM size; when stopped (deallocated), only disks are charged
Consumption: billed per vCPU·second + GiB·second + requests, with a monthly free grantcustom_data Terraform notesA change = VM recreation; cloud-init runs only on first boot
Changing the template (image, environment variables) = new revision; changing a secret does not create a new revision Common misconceptions 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

rg-tf-lab ACA architecture ca-myappingress external · target_port 5000cae-tflab (snet-aca, Consumption profile)probes /healthz · replicas 1–3 identity: id-myapp (UserAssigned)internal TCP 6379ca-redis (added in M5) id-myappPassword comes from a Key Vault reference acrtflab<sfx>User-assigned managed identity log-tflabLog Analytics Basic · admin disabled AcrPull Mounthttps://ca-myapp.<env>.canadacentral.azurecontainerapps.io terraform_data.buildUser's browser local-exec: az acr build (demo)vm-tflab (optional, snet-vm)
cloud-init: docker + nginx demo page

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

Terraform core Sequence diagram: Terraform → provider → ARM → state azurerm plugin RP Microsoft.App gRPC ApplyResourceChange GET …/containerApps/myapp ARM (management) 404 Not Found (can create) PUT (JSON request body) 201 · Azure-AsyncOperation: …/operationStatuses/… · Retry-After Authentication → RBAC → Policy → forward {"status":"InProgress"} … {"status":"Succeeded"} GET operation URL (every N seconds) GET resource (final state) 200 · fqdn, latestRevisionName … NewState (id + all attributes)core updates state → persists to backend
(blob PUT, with lease ID)

Animation

Core animation: the full process of terraform apply creating ca-myapp

Terraform coreCore animation: the full process of terraform apply creating ca-myapp Dependency graph · stateazurerm plugin Entra ID / ARMgRPC server Microsoft.AppAuthentication · RBAC · Policy state bloblab3/myapp.tfstate
Reset
$ terraform apply

Commands

Core commands and parametersCommandPurpose
terraform apply -parallelism=NKey parameters / notesControls the number of resources calling ARM concurrently (default 10)
terraform output -raw app_urlLower 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 tableFor scriptsCheck revision health and traffic
az containerapp logs show -g rg-tf-lab -n ca-myapp --type systemTerraform success ≠ revision health--type console System logs: image pull, probe failures
az acr repository show-tags -n $ACR --repository myappView app output-o table
az vm list-skus -l canadacentral --size Standard_B2s -o tableConfirm the image was built and pushedConfirm the VM size is available and unrestricted in this region
az vm list-usage -l canadacentral -o tableCheck the Restrictions columnCheck 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

Lab 4: deploy myapp with ACR + Container Apps (about 10 minutes; cost: ACR Basic is billed daily, ACA Consumption is mostly within the free grant)
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.
Expected output (excerpt)
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
[1.0.0] Hello from ca-myapp--0000001-6d8f9b7c4-xk2lp, hits=N/A (redis not connected) Change one template field and see a "new revision" 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

, which can be written to terraform.tfvars.
#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).

Command-line tasks
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 table
2. 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
Scenario analysis
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

▶
Introduction to HashiCorp Terraform with Armon Dadgar — HashiCorp, an IBM Company
English · a Terraform co-founder explains how core, providers, and plan/apply work; corresponds to the first half of this module's core animation
▶
Terraform in 100 Seconds — Fireship
English · 100-second quick review
Note No verified dedicated video on deploying Azure Container Apps with Terraform was found.

Official documentation

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
Shot 4 · 75–100s
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.
or score ≥ 70% on the quiz

Module 5 · Identity and secrets: managed identities, role assignments, Key Vault

30:00 – 37:00 · Let apps access resources with identity instead of passwords; keep Terraform-generated passwords only in Key Vault, not in plan or state
7 minephemeral (TF 1.10+) · write-only (TF 1.11+)azurerm value_wo · rbac_authorization_enabled required (5.0)★★★★★
Learning objectives
  • Distinguish system-assigned from user-assigned managed identities, and management-plane from data-plane roles; use azurerm_role_assignment to grant least privilege.
  • Create a RBAC-mode Key Vault (since 5.0, rbac_authorization_enabled must be set explicitly); grant the Terraform identity Secrets Officer and the app identity Secrets User.
  • Use ephemeral random_password + azurerm_key_vault_secret.value_wo to generate and write the Redis password: the value does not go into the plan or state; use value_wo_version to control rotation.
  • Let Container Apps use Key Vault references (secret.key_vault_secret_id + identity) to read secrets; Redis and myapp share one secret.
Prerequisites: The user-assigned identity from M4; the sensitive variables from Lesson 2. Importance:★★★★★

What: three concepts

ConceptDescriptionTerraform
Managed identityAn 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 createdidentity { 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 → resourceazurerm_role_assignment
Key Vault (RBAC mode)The data plane (reading and writing secrets) is also authorized with Azure RBAC, not the legacy access policyazurerm_key_vault + rbac_authorization_enabled = true

The 4 roles used in this lesson (least privilege)

PrincipalRoleScopePurpose
id-myappAcrPullACRPull images (M4)
id-myappKey Vault Secrets UserKey VaultRead secret contents (ACA Key Vault references)
You, running TerraformKey Vault Secrets OfficerKey VaultCreate/update secrets (data plane)
You, running TerraformStorage Blob Data ContributorState storage accountRead/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_secret provides value_wo, together with value_wo_version (an integer; a new value is sent only when it is incremented).

How: this module's data flow

  1. ephemeral "random_password" "redis" Generate a new password on each plan/apply (in memory only).
  2. azurerm_key_vault_secret.redis The value_wo references it; only when is created or value_wo_version changes does the provider PUT the value to https://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.
  3. Both Container Apps' secret blocks reference versionless_id and specify identity = 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.
  4. 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

ApproachValue in plan?Value in state?Use case
variable { sensitive = true } → valueYes (masked display)YesNot recommended for real secrets
resource "random_password" → valueYesYes (result)Legacy approach before Terraform 1.10
data "azurerm_key_vault_secret"YesYesLegacy approach for reading an existing secret, avoiding
ephemeral "random_password" → value_woNoNoRecommended in this lesson: generate and write the secret
ephemeral "azurerm_key_vault_secret" → other *_wo or provider configurationNoNoRead an existing secret to configure a database password or another provider
Bypasses Terraform entirely (the app reads Key Vault / Key Vault references at runtime)NoNoSecrets managed by a security team or rotation system

Comparison with other approaches

Key Vault reference (this lesson)ACA inline secret valueAWS Secrets Manager (Lesson 4)
Value stored inKey Vault, with versioning and auditingIn the Container App resource properties (also goes into state)Secrets Manager
RotationChange the Key Vault version; the platform follows automaticallyRevision restart needed after changing the valueTakes effect after ECS task restart
Terraform stateID onlyContains the valueUse ephemeral + *_wo avoids it
Common misconceptions① "I'm the Owner, so I can read and write secrets" — the Key Vault data plane in RBAC mode requires data roles such as Secrets Officer/User. ② "The ephemeral password changes on every run, so every apply changes Key Vault" — a write-only value is sent only on creation or 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

You (Terraform identity)az login / OIDC id-myappUser-assigned managed identity kv-tflab-<sfx>rbac_authorization_enabledsecret: redis-password(the value only exists here) acrtflab<sfx>myapp · base/redis Secrets Officer Secrets User AcrPull ca-myappsecret redis-password =keyvault ref + identity id-myappenv REDIS_PASSWORD ← secret ca-redisThe same Key Vault referenceredis-server --requirepassinternal TCP 6379 ca-redis:6379 Both apps mount id-myapp; Terraform state holds only the secret ID
Figure 5-1 People and apps both get least privilege via RBAC; no connection strings appear anywhere

Data flow: where traces of the password are left, from generation to container

ephemeralrandom_password.redis(memory only) key_vault_secretvalue_wo (write-only)value_wo_version = 1 Key VaultPUT /secrets/redis-passwordCreate new version Container AppsPlatform reads with id-myappInjects as environment variable Plan file / statevalue_wo = null (write-only) · versionless_id = https://kv-…/secrets/redis-password
Figure 5-2 The value only travels "memory → Key Vault → platform"; state holds only the reference

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….

terraform plan
state (terraform state pull)
Choose an approach.

Core commands and parameters

Command / configurationPurposeNotes
ephemeral "random_password" "x" { length = 32 }Generate a random password without writing it to diskhashicorp/random ≥ 3.7; reference ephemeral.random_password.x.result
value_wo / value_wo_versionwith write-only to write the secret, and trigger updates with an integer versionTerraform ≥ 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 tableList all roles of a principalTroubleshoot 403
az keyvault secret show --vault-name KV -n NAME --query valueManually verify a secret (requires data role)Do not run in a shared terminal
az keyvault list-deleted -o table / az keyvault purge -n KVList/purge soft-deleted Key VaultsWhen a name conflict occurs (M8)
terraform state pull | grep -c "$PW"Verify the secret is not in state0 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)

Write secrets.tf and modify myapp (see the "Commands" tab), then observe the write-only display in plan
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.
Apply and verify the counter
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.

Prove the password is not in state
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).

Rotate the password: increment the version number; Terraform generates a new random value and writes it as a new Key Vault version; the platform then refreshes the reference and restarts the revision.
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.

(Optional, billed hourly) Azure Managed Redis: azurerm 5.x provides 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.

Command-line tasks
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 table
2. 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 outputs
Scenario analysis
Audit 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

▶
Microsoft Azure Managed Identity Deep Dive — John Savill's Technical Training
English · how managed identities work, the difference between system-assigned and user-assigned, and how tokens are obtained
Note No verified video explaining Terraform ephemeral resources and write-only arguments was found.

Official documentation

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–75s
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.
Shot 4 · 75–90s
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.
or score ≥ 70% on the quiz

Module 6 · Azure Verified Modules and azapi

37:00 – 45:00 · Don't reinvent the wheel: use Microsoft-maintained AVM modules; when azurerm lags behind an API, talk to ARM directly with azapi
8 minazapi 2.13.0 · AVM (registry: Azure/avm-res-*)Note the AVM azurerm < 5.0 constraint★★★★☆
Learning objectives
  • 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 requires azurerm < 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.
Prerequisites: Modules, version constraints, and the lock file from Lesson 2. Importance:★★★★☆

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:

TypeExamplePurpose
Resource module avm-resavm-res-network-virtualnetwork,avm-res-keyvault-vault,avm-res-app-containerappone primary resource + common add-ons (locks, role assignments, diagnostics, private endpoints), following WAF defaults
Pattern module avm-ptnLanding Zone, Hub-Spoke, etc.architecture patterns made of multiple resources (Lesson 6)
Utility module avm-utlregion info, naming, etc.helper-function type

Some module versions and provider dependencies verified on 2026-11-15

ModuleVersion (release date)Provider dependencyCan coexist with an azurerm 5.x root module
avm-res-network-virtualnetwork0.23.0 (2026-11-04)azapi ~> 2.12✓ (does not depend on azurerm)
avm-res-app-managedenvironment0.6.0 (2026-10-23)azapi ~> 2.12,time✓
avm-res-app-containerapp0.9.0 (2026-05-14)azapi ~> 2.5,modtm,random✓
avm-res-storage-storageaccount0.11.0 (2026-11-04)azapi ~> 2.12✓
avm-res-keyvault-vault0.13.1 (2026-11-11)azapi ~> 2.12,azurerm >= 4.81, < 5.0✗ Conflict
avm-res-containerregistry-registry0.9.0 (2026-10-29)azurerm >= 4.81.0, < 5.0.0✗ Conflict
avm-res-managedidentity-userassignedidentity0.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

ParameterMeaningExample
type<resource type>@<api-version>Microsoft.App/managedEnvironments@2024-03-01
parent_idParent resource ID (resource group, subscription, or parent resource)azurerm_resource_group.lab.id
name / locationResource name and region
bodyARM request body (HCL object){ properties = { … } }
response_export_valuesPath exported from the response; the result is in .output["properties.defaultDomain"]

When: selection rules

SituationChoice
azurerm fully supports it and the team is familiar with itazurerm resource (most readable, clear plan diffs)
Needs enterprise-grade defaults and multiple supporting resources, and the module's provider constraints are compatible with yoursAVM resource module (pin an exact version; 0.x versions may have breaking changes)
azurerm lacks a certain attributeazurerm resource + azapi_update_resource patch (make sure the two do not manage the same attribute)
New resource type / preview API / not yet supported by azurermazapi_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)
Common misconceptions① “AVM is a 1.0 stable release”: most Terraform AVM modules are still 0.x, and minor-version upgrades can include breaking changes, so they must be locked 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

azurerm_key_vaultHand-written schema · friendly field names module "avm-res-…"Implemented internally with azurerm or azapi azapi_resourcetype@api-version + body provider plugin azurerm: go-azure-sdkFixed api-version AVM itself is not a providerit calls one of the two above azapi: built-in schema validationAny api-version Azure Resource ManagerPUT/GET/PATCH/DELETE/subscriptions/…/providers/Microsoft.X/type?api-version
Figure 6-1: all of them sit on the same ARM REST layer; the difference is who maintains the schema and api-version

Version constraint intersection: why init fails

Root moduleazurerm ~> 5.14 → [5.14, 6.0) avm-res-keyvault-vault 0.13.1azurerm >= 4.81, < 5.0 avm-res-network-virtualnetworkDepends only on azapi ~> 2.12 Intersection = ∅ → no available releases matchFix: switch to a pure-azapi module / wait for the module to upgrade / split the root module / write it yourself with azurerm resources
Figure 6-2: a provider version can only be selected once across the entire root module (including all submodules)

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.

Waiting for answer…

Core commands and flags

CommandPurposeNotes
terraform initDownloads modules and providers, resolves version constraintsReports errors on conflict no available releases match the given constraints
terraform providersLists the provider constraint tree by moduleFinds which module requires it < 5.0
curl -s https://registry.terraform.io/v1/modules/Azure/<m>/azurermChecks the latest module version and dependenciesView root.provider_dependencies
az provider show -n Microsoft.App --query "resourceTypes[?resourceType=='managedEnvironments'].apiVersions" -o tsvLists the api-versions available for a resource typeChooses a version for azapi
terraform state show 'module.vnet.azapi_resource.vnet'Views resources inside a moduleAddresses 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)

Create a VNet with the AVM module (separate directory)
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.subnet
Reproduce the provider version conflict: in the same directory, add the Key Vault AVM module and run only init (no apply).
cat >> 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"
Back to the main lab: read runtime attributes with azapi
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"
}
Query available api-versions (to choose a version for azapi)
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.

Clean up the AVM demo
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.

Command-line exercises
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.vaultUri
Scenario analysis
The 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

▶
Azure Verified Modules Overview — John Savill's Technical Training
English · AVM goals, module types, Bicep and Terraform versions
▶
Introducing Azure Verified Modules for Terraform — Ned in the Cloud
English · Using AVM with Terraform
▶
Getting Started With: Azure Verified Modules — Code To Cloud
English · Getting-started demo
▶
Building Secure, Well‑Architected Azure Workloads with Azure Verified Modules and GitHub Copilot — ITOpsTalk
English · Azure Infra Summit 2026 talk

Official documentation

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–50s
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.
Shot 3 · 50–75s
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.
or score ≥ 70% on the quiz

Module 7 · Cloud troubleshooting in practice

45:00 – 53:00 · First identify which layer the error comes from (authentication / authorization / ARM validation / resource provider / Terraform state), then fix the root cause
8 minutesTF_LOG · import block · time_sleepInteractive troubleshooting tree★★★★★
Learning objectives
  • 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, and import blocks to locate and fix issues.
Prerequisites: M1–M5. Importance:★★★★★

What: which layer the error comes from

LayerTypical errorsHTTPReported byWhat to check first
① Authentication (acquiring a token)subscription ID could not be determined,AADSTS…,az: not found—provider local / Entra IDenv | grep ARM_,az account show
② Authorization (RBAC / Policy)AuthorizationFailed,RequestDisallowedByPolicy,ForbiddenByRbac403ARM / data planethe action and scope in the error; az role assignment list
③ Subscription capabilityMissingSubscriptionRegistration,NoRegisteredProviderFound409/400ARMaz provider show
④ Capacity / quotaOperationNotAllowed … exceeding approved … quota,SkuNotAvailable,MaxNumberOfRegionalEnvironmentsInSubExceeded409/400resource provideraz vm list-usage,az vm list-skus
⑤ Resource conflictalready exists - to be managed via Terraform this resource needs to be imported,StorageAccountAlreadyTaken,VaultAlreadyExists200 (existence check) / 409provider / RPWho created the resource? Was it soft-deleted?
⑥ Eventual consistencyPrincipalNotFound, first ForbiddenByRbac, image pull unauthorized400/403ARM / data planeDoes a rerun succeed? Was the identity/role just created?
⑦ Long-running operation failurepolling after Create: … Failed, timeout—RP async resultactivity 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

FailureRoot causeFixPrevention
Authentication failureNo subscription, CLI session expired, OIDC subject mismatchSet ARM_SUBSCRIPTION_ID,az login, fix the federated credentialIn CI, use ARM_USE_CLI=false, which makes errors more direct.
403 AuthorizationFailedThe 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 importCreated manually in the portal, resources left by a previous failed apply, managed by another stateimport block + confirm in plan that there are no destructive changesProhibit write permissions in the portal; persist_id_on_create_before_polling_for_completion
QuotavCPU quota for a VM family in the region, ACA environment count, etc.Change SKU/region, or request a quota increaseCheck before go-live list-usage; pre-request in the Landing Zone
RP not registered5.0 does not register RPs by defaultaz provider register or resource_providers_to_registerregister in the subscription provisioning process
Eventual consistencyNew service principal not yet replicated, role assignment not yet effectiveSet the role assignment principal_type; add time_sleep; rerunPut 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 for PUT https://management.azure.com to 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 Failed check the detailed reason returned by the RP.
  • “exists in Azure, not in state”: import block (Terraform 1.5+); 1.7+ supports using for_each.
Common misconceptions① “Just grant Owner on a 403”: first read the action in the error and grant access as needed; granting Owner hides design problems. ② “If it already exists, delete the resource in Azure”: this may delete production data; first confirm who created it, and import it if possible. ③ “-target fixes everything”: -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

terraformstate / configuration ① AuthenticationEntra token ② AuthorizationRBAC · Policy ③ SubscriptionRP registration ④ RP validationQuota · SKU · name ⑦ Asyncprovisioning result ⑤ already exists(existence check GET) AADSTS… /subscription ID… 403 AuthorizationFailedRequestDisallowedByPolicy MissingSubscriptionRegistration OperationNotAllowed(quota) · SkuNotAvailable polling … Failedcheck the reason in the activity log ⑥ Eventual consistency: spans ②③④PrincipalNotFound · first-attempt ForbiddenByRbac · image pull unauthorized
Figure 7-1: error codes tell you which layer the request got stuck at

import fix workflow

already existsCopy the ID from the error Write an import blockto + id terraform plan1 to import, 0 destroy? Adjust configurationEliminate differences applyRemove import block
Figure 7-2: first confirm in plan that it is “import only, no replacement”, then apply

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).

RBAC propagation delay: 120s
Set the conditions, then click Run.
$ terraform apply

Troubleshooting toolbox

CommandPurposeNotes
TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform applyRecord the full interaction between provider and ARMTF_LOG_PROVIDER Log provider only; logs are sensitive
az monitor activity-log list -g rg-tf-lab --status Failed --offset 1hView failed ARM operations and detailed reasons--query "[].{op:operationName.value,msg:properties.statusMessage}"
az role assignment list --assignee ID --allView all roles of a principalOn 403, verify the scope
az provider show -n NS --query registrationStateRP registration statusWait while Registering
az vm list-usage -l LOC / az quota listQuota usageaz quota Requires an extension; see the documentation
az vm list-skus -l LOC --size X --query "[].restrictions"Whether the SKU is restrictedNotAvailableForSubscription
az resource show --ids ID --query properties.provisioningStateActual state of the resource after an async failureDecide whether to import or delete
terraform plan -generate-config-out=gen.tfAutomatically generate a configuration draft for import blocksTerraform 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)

Failure 1: resource already exists (created manually in the portal/CLI) → import
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.

Failure 2: 403 insufficient permissions (demonstrate with a service principal that has only Contributor; if you cannot create a service principal, just read the output)
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.

Failure 3: resource provider not registered (read-only demo: check which RPs are not registered and understand the error)
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.

Failure 4: quota / SKU unavailable
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.

Wrap-up: confirm the main lab has no drift.
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).

Command-line exercises
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 jsonc
2. 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.tf
Scenario analysis
The 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

▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · includes chapters on import, state, etc.; useful as a review of troubleshooting basics
Note No verified video was found that specifically covers Terraform troubleshooting on Azure (RBAC propagation, RP registration, quota).

Official documentation

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–80s
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.
or score ≥ 70% on the quiz

Module 8 · Cost, cleanup and self-check

53:00 – 60:00 · Know where each resource is billed; destroy runs in reverse dependency-graph order; finally check for soft-deleted items and “automatically appearing” leftovers
7 minutesterraform destroy · tags · budgetSoft delete · NetworkWatcherRG · ME_ resource groups★★★★☆
Learning objectives
  • 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 provider features affects 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.
Prerequisites: M1–M7. Importance:★★★★☆ (forgetting cleanup is the most expensive mistake in cloud learning)

What: billing points for this lesson's resources

ResourceBilling modelUsage in this lessonNotes
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 = 1Always-on replicas keep consuming the allowance; when not in use, set min_replicas = 0 (not suitable for Redis)
Managed resources of the VNet-integrated environmentME_… Standard load balancer and standard public IP in the resource group1 setOfficial docs say this part is billed separately from Container Apps
ACR BasicFixed daily charge + storage1Billed daily even when unused
Log AnalyticsBilled per GB ingested (PerGB2018) and retentionVery littleNearly zero in a demo environment
Key Vault StandardBilled per operationVery littlenegligible
Storage account (state)Capacity + transactions; ZRS costs more than LRSA few KBnegligible; keep until the end of the course
Linux VM (optional)Billed per second by size + managed disk + standard public IPDelete after finishing“Stopped” does not mean “deallocated”; only deallocated VMs stop incurring compute charges
Azure Managed Redis (optional)Billed per instance-hourDelete after finishingThe 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 NetworkWatcherRG automatically; ACA, in ME_… 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 = true will 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_destroy default false); blob/container soft delete in storage.
  • Independent lifecycle: the state storage account is in rg-tfstate, and has a CanNotDelete lock; 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/expires tags, combined with budget alerts and scheduled cleanup scripts (Lesson 5 automation).
  • Whole course finished: delete rg-tfstate (delete the lock first), clean up NetworkWatcherRG (if it was created in this lesson and there are no other VNets in the subscription).
Common misconceptions① “Deleting the resource group means it's clean”: soft-deleted Key Vault names are still taken, Network Watcher is in another resource group, and the state account is in another resource group. ② “A shut-down VM is not charged”: shutting down inside the OS only means “stopped”, and compute charges still apply; you need to 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)

① ca-myapp ① ca-redis ② kv secret · role assignment ② cae-tflab (environment) ③ Key Vault (purge) ③ ACR · UAMI · LAW ③ NSG association · subnet ④ VNet ⑤ rg-tf-labrejected if not empty Parallel deletion within the same layer (limited by -parallelism); after the environment is deleted, the platform reclaims the ME_ managed resource group
Figure 8-1: delete consumers first, then infrastructure; delete the resource group last

Cleanup scope: what Terraform manages and what it does not

terraform destroy handles all declared resources in rg-tf-lab (including the optional VM/Redis)Key Vault (features: purge on destroy)ACA environment (the platform reclaims the ME_… resource group along with it)AVM demo (destroy separately in ~/tf-lab3-avm) Needs manual check / cleanup rg-tfstate (state account + CanNotDelete lock): delete after the course endsNetworkWatcherRG / NetworkWatcher_canadacentralSoft delete: Key Vault (if purge fails), Log Analytics workspaceLocal machine: ~/tf-lab3.env, .terraform, plan files, tf.log
Figure 8-2: destroy only deletes resources that are in state

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.

Resource retention time: 8 hours
terraform destroy
$ terraform destroy

Core commands and flags

CommandPurposeNotes
terraform plan -destroyPreview resources to be deletedLook carefully before deleting
terraform destroyDelete all resources in state-target Delete only some (emergency)
az resource list -g rg-tf-lab -o tableCheck for leftovers in the resource groupWhen destroy fails
az group list --query "[?starts_with(name,'ME_')]"View the ACA managed resource groupShould disappear after the environment is deleted
az keyvault list-deleted / az keyvault purgeSoft-deleted Key VaultCannot be purged when purge protection is on
az monitor log-analytics workspace list-deleted-workspacesSoft-deleted workspaceAutomatically restored when recreated with the same name
az group delete -n RG --yes --no-waitLast resort: delete the resource group directlyThen clean up state
az lock deleteDelete the resource lockBefore 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)

Preview and run destroy
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.
Check for leftovers
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.

(when the whole course is finished) delete the state storage account: Lesson 4 onward still uses the remote state concept, but this lesson's account can be deleted.
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
Local cleanup: ~/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>.

Command-line exercises
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
Scenario analysis
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

▶
Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners — freeCodeCamp.org
English · destroy and rebuild process at the end of the course
Note No verified video was found that specifically covers Azure lab cost control and Terraform cleanup.

Official documentation

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
or score ≥ 70% on the quiz

Command cheat sheet

Terraform 1.17 · azurerm 5.14 · azapi 2.13 · every code block can be copied with one click
Post-class reference

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 table

Container 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 codeWhat to do firstCommon cause → fix
subscription ID could not be determinedenv | grep ARM_Subscription not set → ARM_SUBSCRIPTION_ID
Unsupported argument "skip_provider_registration"Check provider versionRemoved in 5.0 → resource_provider_registrations
MissingSubscriptionRegistrationaz provider showNot registered by default in 5.0 → register RP
AuthorizationFailed (403)Read the action/scope in the errorMissing role → least privilege
AuthorizationPermissionMismatch (state)Role on the containerMissing Storage Blob Data Contributor
KeyBasedAuthenticationNotPermittedbackend configurationAdd use_azuread_auth = true
Error acquiring the state lock, confirm the lock holderConcurrent run or leftover → wait / force-unlock
already exists - … needs to be importedaz resource showManually created or last attempt failed → import block
ForbiddenByRbac (Key Vault)Data-plane roleMissing Secrets Officer/User or not yet propagated → authorize + time_sleep
PrincipalNotFoundWas the principal just created?replication delay → principal_type
OperationNotAllowed … quotaaz vm list-usageInsufficient quota → change SKU / request
revision Unhealthy / upstream connect errorSystem logstarget_port, probes, image
no available releases match … < 5.0.0, ~> 5.14terraform providersAVM 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

From an empty subscription to an accessible myapp: one apply delivers VNet + ACR + Container Apps + Key Vault + Redis; after verification, one destroy
Post-class ≈ 40 minutesCombines all modulesCost: a same-day destroy usually costs under a few dollars
Scenario You are a platform engineer and need to deliver the Docker course's myapp to Azure (canadacentral). Requirements: ① state is in a storage account and only Entra ID access is allowed; ② networking is generated by for_each, and the ACA environment is VNet-integrated; ③ the app pulls ACR images without passwords using a user-assigned identity; ④ the Redis password is generated by Terraform, but must not appear in the plan or state; ⑤ deliver everything with one 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.
Prerequisites: new directory + reuse the state account (Modules 0, 1, 2)
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.

Run plan and do a security review (Modules 4, 5)
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
Deliver the full stack with one apply
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.

Acceptance: functionality + security (Modules 2, 4, 5)
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
Drift and idempotency (Modules 3, 7)
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 corrected
Rotate password (Module 5)
sed -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
destroy and leftover check (Module 8)
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).

Acceptance checklist

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

Verification basis for all technical facts in this lesson (verified on 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
Terraform CLILatest 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.11terraform releases · Ephemeral resources
azurerm versionLatest 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 changessubscription 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 deprecated4.0 Upgrade Guide
azurerm 5.0 changesresource_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 removed5.0 Upgrade Guide(GitHub website/docs/guides/5.0-upgrade-guide.html.markdown)
azurerm authentication and featuresuse_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_resourcesprovider documentation · features block
resource argumentsazurerm_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_rediscontainer_app · key_vault_secret · role_assignment
azurerm backendEntra 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 lockingBackend Type: azurerm (v1.17.x)
random / time providerrandom 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
azapi2.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),retryazapi_resource
AVM modulesavm-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 networkingworkload 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 VNetCustom virtual networks(updated 2026-05-19) · Ingress overview(2026-10-22)
Sample apps and lab scenariosmyapp (Flask + Redis, port 5000, /healthz), internal TCP Redis + Key Vault reference, corresponding to Docker lesson 3Docker 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 name env: 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_sleep the 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-exec building 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.