Terraform Hour 6: Infrastructure Architecture in Practice

From “writing Terraform” to “designing an IaC repository that can evolve, be audited, and keep its blast radius under control”: environment layout · module interfaces · state splitting · multi-region and multi-account · secrets · zero downtime · import and migration · architecture review
Terraform v1.17.2aws 6.73 · azurerm 5.14kreuzwerker/docker 4.7.0Terragrunt v1.2.2Verified against official docs · 2026-11
Overall Learning Objectives
  • For a real product (myapp), choose repository and environment layout: monorepo vs. polyrepo, per-environment directories vs. CLI workspaces vs. Terragrunt (v1.2.2), and be able to state the failure mode of each.
  • Design a layered structure of thin root modules, composition modules, and reusable leaf modules, use dependency injection (pass IDs as inputs instead of looking them up inside modules) to avoid “god modules”, and publish modules with semantic versioning.
  • Split one large state into network / platform / application three layers, choosing suitable cross-stack reference methods (terraform_remote_state, data source lookups, SSM / App Configuration parameter store), and control read permissions on outputs.
  • Use provider alias, AWS provider 6.x resource-level region region parameters for multi-region management; understand AWS Organizations / Azure management groups and the “landing zone”, and know that the Terraform provider does not support for_each (OpenTofu does).
  • Use Terraform 1.10's ephemeral resources and 1.11's write-only arguments (password_wo,value_wo) keep passwords out of plan/state, and evaluate how to handle “secrets already in state”.
  • Use create_before_destroy, name suffixes, health checks and traffic switching to implement zero-downtime replacement and blue/green deployment, and understand why database changes cannot be handed to a single apply.
  • Use import import block + -generate-config-out to bulk-adopt ClickOps resources and understand the 1.14 introduced list blocks and terraform query; finally, use a architecture review checklist and failure-mode analysis to review the whole design.

1-hour time allocation table

#TimeModuleCore ContentAnimation / InteractionLab (local Docker + MinIO)
0Before classPreparation: sample repository structureStart MinIO (simulated S3), build myapp:1.0, generate myapp-infra repository skeletonEnvironment self-check checklistMinIO bucket tfstate writable
100–07Repository and environment layoutmonorepo/polyrepo, per-environment directories vs. workspaces vs. Terragrunt, componentization (component/stack)Layout selector: answer 5 questions to get a recommended layout and its risksThe same code deployed to two directories (dev/stage) with two state keys
207–16Module composition and interface designthin root modules, composition modules, dependency injection, avoiding god modules, input validation, semantic versioningModule dependency graph: god module vs. composition module, “how many resources a single change affects”Split myapp into three modules (network / redis / web-service) and compose them
316–24State splitting and cross-stack referencesblast radius, splitting dimensions,terraform_remote_state vs. data sources vs. parameter store, read permissionsCore animation: dependencies and output passing between multiple state stacks (S3 GetObject → outputs → plan)Three-layer state stored in MinIO; the application layer reads network/platform layer outputs
424–32Multi-region and multi-account/subscriptionprovider alias, AWS 6.x resource-level region, providers do not support for_each, Organizations / management groups, landing zoneMulti-account assume-role path animationLocal simulation of two “regions” (two Docker networks + two sets of provider configuration)
532–40Secrets: ephemeral and write-onlyephemeral block (1.10), write-only argument (1.11),_wo_version, handling sensitive data in stateValue flow tracing: which of the four cases (normal / sensitive / ephemeral / write-only) goes into stateCompare random_password and ephemeral "random_password" footprint in state
640–47Zero-downtime changes and blue/greencreate_before_destroy, name conflicts, health checks, DNS/traffic switching, database changesCore animation: default replacement vs. create_before_destroy timing and availabilitynginx + blue/green pair of myapp containers, switching active_color zero interruption
747–54Importing existing resources and migrationimport blocks (for_each batching),-generate-config-out the ClickOps migration workflow,list blocks and terraform query (1.14+)Migration pipeline: discover → import → generate → converge → zero diffTake docker run manually created containers/networks, import them, and generate code
854–60Comprehensive architecture reviewreview checklist, failure mode analysis (FMEA), anti-patterns, troubleshooting treeInteractive review scoring + architecture troubleshooting decision treeReview the capstone lab repository
—After classCheat sheet · Capstone labDesign a complete repository for myapp with 9 states in total: dev/stage/prod × network/platform/applicationFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / syntaxLab
Choose repository and environment layout✓·✓✓···✓-chdir,-backend-config,workspaceM1 two environments
Design module interfaces and versions·✓·✓···✓validation,source = "git::…?ref=v1.2.0"M2 three modules
Split state, control blast radius✓·✓···✓✓state mv,removed,importM3 three-layer state
Cross-stack references and permissions··✓✓···✓terraform_remote_state,aws_ssm_parameterM3
Multi-region / multi-account / multi-subscription·✓·✓···✓alias,configuration_aliases,assume_roleM4
Secrets not stored in state··✓·✓··✓ephemeral,*_wo,*_wo_versionM5
Zero-downtime replacement / blue-green·····✓·✓create_before_destroy,replace_triggered_by,-replaceM6 blue/green
Import and migrate existing resources··✓···✓✓import {},-generate-config-out,terraform queryM7
Architecture review and failure mode analysis·······✓review checklist,plan -jsonCapstone lab

Topics excluded from this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
Terraform language basics, basic state concepts, backend initializationPrerequisitesLesson 1,Lesson 2
Full deployment details of myapp on Azure / AWS (VNet, Container Apps, VPC, ECS)This lesson only references its outputs in the “corresponding cloud code”Lesson 3 (Azure),Lesson 4 (AWS)
CI/CD pipelines, OIDC, Policy as Code, drift detectionbelongs to automation and operationsLesson 5
performance tuning (-parallelism,-minimal-refresh), state corruption recovery, provider debug logsbelongs to advanced troubleshootingLesson 7
Full authoring of HCP Terraform Stacks (.tfcomponent.hcl / .tfdeploy.hcl)Depends on HCP Terraform; this lesson only compares conceptsOfficial Stacks documentation
IaC for resources inside a Kubernetes cluster (Helm provider, GitOps)Different delivery modelsKubernetes course

How to use this course material

10 pages per module
Theory · Diagrams · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Audio · Video. For architecture lessons, the suggested order is: theory → diagrams → animation → production case, then hands-on lab.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. It is saved in this browser (cleared on refresh when local storage is disabled).
Chinese audio
The “Audio” page uses the browser's built-in Web Speech API (en-US) to read the narration aloud; without a Chinese voice pack, the narration can still be read or passed to a TTS tool.
Version notes This lesson uses Terraform CLI v1.17.2 (2026-11-11) as the baseline. Language feature versions have been checked against the official CHANGELOG and docs: ephemeral resources 1.10; write-only arguments 1.11; list blocks and terraform query,action blocks 1.14.0 (2025-11-19); variable/output deprecated attribute, module source/version can use variables and locals 1.15.0 (2026-04-29); in-module import block 1.16.0 (2026-08-26); variables/locals in provider requirements,-minimal-refresh Terraform Policy GA 1.17.0 (2026-10-21). Providers: hashicorp/aws 6.73.0, hashicorp/azurerm 5.14.0 (note: azurerm is now at 5.x; since 5.0 it no longer registers resource providers automatically by default), kreuzwerker/docker 4.7.0, hashicorp/random 3.9.1. Terraform's provider block currently does not support for_each/count, unlike OpenTofu (see Module 4).

Module 0 · Preparation: sample repository structure (complete before class)

Start a local “cloud”: Docker Engine acts as compute and networking, MinIO acts as the remote S3 state; then generate the myapp-infra repository skeleton
Before class ≈ 10 minFully local · zero cloud cost
Prerequisites
  • CompletedLesson 5(CI/CD and OIDC). The capstone lab repository in this lesson can plug directly into the Lesson 5 GitHub Actions pipeline: each state directory is one “job unit” in the pipeline matrix.
  • Workstation: Ubuntu 24.04 LTS (Azure VM or local machine), Docker Engine 29 (from the Docker lesson), Terraform CLI 1.17.x. Windows / macOS with Docker Desktop also works (note that the docker provider's host address differs, see below).
  • Optional: AWS CLI v2 / Azure CLI, needed only when reading the “corresponding cloud code”; all labs in this lesson can be done without logging in to any cloud.

Step 1: Check tool versions

terraform version
docker version --format 'Docker Engine {{.Server.Version}}'
docker info --format '{{.OperatingSystem}} / cgroup {{.CgroupVersion}}'
Terraform v1.17.2
on linux_amd64
Docker Engine 29.9.3
Ubuntu 24.04.3 LTS / cgroup 2

Step 2: Start MinIO (S3-compatible object storage, holding 9 states)

Lesson 2 demonstrated remote state with MinIO. If the container is still there, you can reuse it directly; otherwise, rebuild it as shown below. Note the image change: MinIO's official community edition has stopped publishing Docker images since 2025-10, and the repository was archived in 2026,docker pull minio/minio so it is no longer reliable. This lesson uses the community fork pgsty/minio (AGPLv3, continues to publish images; latest tag verified 2026-11 RELEASE.2026-08-04T00-00-00Z). It is for lab use only; store production state in S3 / Azure Blob / HCP Terraform.

docker network create tf-lab 2>/dev/null || true
docker volume create tf-minio-data
docker run -d --name tf-minio --network tf-lab --restart unless-stopped \
  -p 9000:9000 -p 9001:9001 \
  -e MINIO_ROOT_USER=tfadmin -e MINIO_ROOT_PASSWORD='tfadmin-Lab-2026' \
  -v tf-minio-data:/data \
  pgsty/minio:RELEASE.2026-08-04T00-00-00Z server /data --console-address ":9001"

# Create the bucket with the official AWS CLI image (no dependency on the mc client)
docker run --rm --network tf-lab \
  -e AWS_ACCESS_KEY_ID=tfadmin -e AWS_SECRET_ACCESS_KEY='tfadmin-Lab-2026' -e AWS_DEFAULT_REGION=us-east-1 \
  amazon/aws-cli --endpoint-url http://tf-minio:9000 s3 mb s3://tfstate
docker run --rm --network tf-lab \
  -e AWS_ACCESS_KEY_ID=tfadmin -e AWS_SECRET_ACCESS_KEY='tfadmin-Lab-2026' -e AWS_DEFAULT_REGION=us-east-1 \
  amazon/aws-cli --endpoint-url http://tf-minio:9000 s3api put-bucket-versioning --bucket tfstate --versioning-configuration Status=Enabled
make_bucket: tfstate

Enabling bucket versioning is a hard requirement for production state storage (allows rollback after accidental deletion or overwrite). Web console: http://localhost:9001.

Step 3: Set credential environment variables (both the S3 backend and remote_state read them)

cat > ~/.tf-lab.env <<'EOF'
export AWS_ACCESS_KEY_ID=tfadmin
export AWS_SECRET_ACCESS_KEY='tfadmin-Lab-2026'
export AWS_REGION=us-east-1
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"
EOF
mkdir -p "$HOME/.terraform.d/plugin-cache"
source ~/.tf-lab.env

TF_PLUGIN_CACHE_DIR Let the 9 state directories share one copy of the provider binary, avoiding a download in each directory.

Step 4: Prepare the myapp:1.0 image (from the Docker lesson)

If docker image inspect myapp:1.0 succeeds, skip this step. Otherwise, rebuild it with the minimal version below (Flask + gunicorn + Redis counter + /healthz, listening on 5000, reading REDIS_HOST, also outputting APP_VERSION and APP_COLOR for the Module 6 demo):

mkdir -p ~/myapp-src && cd ~/myapp-src
cat > app.py <<'EOF'
import os, socket
from flask import Flask
import redis
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=int(os.getenv("REDIS_PORT", "6379")), socket_timeout=1)
@app.get("/")
def index():
    try:
        n = r.incr("hits")
    except redis.exceptions.RedisError:
        n = -1
    return f"myapp v{os.getenv('APP_VERSION','?')} env={os.getenv('APP_ENV','dev')} color={os.getenv('APP_COLOR','none')} host={socket.gethostname()} hits={n}\n"
@app.get("/healthz")
def healthz():
    return "ok\n"
EOF
cat > requirements.txt <<'EOF'
flask==3.1.*
gunicorn==23.*
redis==6.*
EOF
cat > Dockerfile <<'EOF'
FROM python:3.13-slim
ARG APP_VERSION=1.0
ENV APP_VERSION=$APP_VERSION
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
USER 10001
EXPOSE 5000
CMD ["gunicorn", "-b", "0.0.0.0:5000", "-w", "2", "app:app"]
EOF
docker build --build-arg APP_VERSION=1.0 -t myapp:1.0 .
docker build --build-arg APP_VERSION=1.1 -t myapp:1.1 .
docker image ls myapp --format '{{.Tag}} {{.ID}}'
1.1 5d0c9e2b7a41
1.0 a83f1c6d2e90

The two tags' APP_VERSION IDs differ, so the image IDs differ — Module 6 relies on a change in the image ID to trigger container replacement. If you reuse myapp:1.0 from the Docker lesson, confirm that its ID differs from 1.1's.

Step 5: Generate the myapp-infra repository skeleton

mkdir -p ~/myapp-infra && cd ~/myapp-infra
git init -q
mkdir -p modules/{network,redis,web-service,myapp-stack} \
         live/{dev,stage,prod}/{10-network,20-platform,30-app} \
         bootstrap docs/adr
cat > live/backend.s3.hcl <<'EOF'
# Backend arguments shared by all states; each directory writes only its key in its own backend.tf
bucket                      = "tfstate"
region                      = "us-east-1"
endpoints                   = { s3 = "http://localhost:9000" }
use_path_style              = true
use_lockfile                = true
skip_credentials_validation = true
skip_requesting_account_id  = true
skip_metadata_api_check     = true
skip_region_validation      = true
skip_s3_checksum            = true
EOF
cat > .gitignore <<'EOF'
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log
generated*.tf
EOF
tree -d -L 3 .
.
├── bootstrap
├── docs
│   └── adr
├── live
│   ├── dev
│   │   ├── 10-network
│   │   ├── 20-platform
│   │   └── 30-app
│   ├── prod
│   │   ├── 10-network
│   │   ├── 20-platform
│   │   └── 30-app
│   └── stage
│       ├── 10-network
│       ├── 20-platform
│       └── 30-app
└── modules
    ├── myapp-stack
    ├── network
    ├── redis
    └── web-service
Naming convention Directory prefix 10-/20-/30- indicates the deployment order (lower layers before upper layers); state keys are uniformly <env>/<layer>/terraform.tfstate, for example prod/20-platform/terraform.tfstate. This convention will be used directly in the Module 3 terraform_remote_state block: the key is the stack-to-stack “interface address”, so do not change it casually once set.
About S3-compatible storage The official docs state that the S3 backend is only tested against Amazon S3; for other S3-compatible implementations it is “best effort”. use_lockfile = true relies on S3 conditional writes (If-None-Match); if your MinIO version does not support it, locking will fail or error out; in that case, you can temporarily remove that line in the lab and make sure only one person runs at a time. DynamoDB lock (dynamodb_table) has been officially marked as deprecated.
Windows / macOS (Docker Desktop) the docker provider connects to by default unix:///var/run/docker.sock; on Windows, you can set it in provider "docker" the config host = "npipe:////./pipe/docker_engine".

Warm-up: answer from memory (30 seconds)

Can you use variables inside a backend block?

No. The backend configuration is loaded before variables are evaluated, so use -backend-config=FILE or -backend-config="key=value" for a “partial configuration”. This is exactly why each directory in this lesson writes only the key, with the other arguments kept in the shared backend.s3.hcl file. This is the reason. (Since 1.15, module source can use variables, but backend still cannot.)

terraform apply — what does state locking protect?

Prevents two processes from reading and writing the same state at the same time. The S3 backend's native lock writes a .tflock object. The lock only protects “the same state”; concurrency and ordering across states must be handled by architecture (Module 3 of this lesson) and pipelines.

Environment self-check checklist

Module 1 · Repository and Environment Layout

00:00 – 07:00 · Directory structure is not a matter of taste: it determines state boundaries, approval granularity, and how much damage a single mistake can do
7 minTerraform 1.17 · Terragrunt v1.2.2★★★★★
Learning objectives
  • Compare the trade-offs between monorepo and polyrepo in terms of permissions, release cadence, and code reuse.
  • Explain how the three multi-environment approaches actually work: per-environment directories (one root module and one state key per directory),CLI workspace (same code, state path with a prefix env:/<ws>/),Terragrunt (an outer orchestrator generates the backend and inputs,terragrunt run --all).
  • Split infrastructure into “components (component / stack)” that can be deployed independently, and define naming and directory conventions for them.
Prerequisites: backend partial configuration (-backend-config), module calls. Importance:★★★★★ (changing the layout later = large-scale state migration)

What: four questions a repository layout must answer

  1. How many repositories should the code live in? (monorepo / polyrepo / module repo + instance repo)
  2. How are environments isolated from each other? (directories / workspaces / an outer tool / separate accounts or subscriptions)
  3. What does one state contain? (component boundaries; covered in depth in Module 3)
  4. Where do the differences live? (tfvars, root module parameters within the directory, Terragrunt inputs)

Why: why “one directory + one state for everything” does not survive half a year

  • Blast radius: A single apply can touch more resources, raising the cost of an accidental deletion or provider bug; plan is also slower (refreshing thousands of resources).
  • Permissions: Someone who can change the application should not necessarily be able to change the VPC or firewall; a shared state means a shared set of credentials.
  • Release cadence: Networking changes a few times a year and applications change several times a day; bundling them together means every release carries network risk.
  • Environment drift: If dev and prod are not “the same code + different parameters”, prod will eventually have configuration that dev never tested.

How: how the three multi-environment approaches actually work

ApproachCodeState location (S3 backend)How differences are injectedTypical commands
Per-environment directories
(recommended in this lesson)
live/dev/30-app/main.tf Calls modules/web-service; each directory is an independent root moduleper-directory backend key differ: dev/30-app/terraform.tfstatewithin the directory terraform.tfvars or written directly in module argumentsterraform -chdir=live/dev/30-app plan
CLI workspaceSame directory, same codeThe default workspace uses key; other workspaces are stored at env:/<ws>/<key> (the prefix is controlled by workspace_key_prefix , which defaults to env:)terraform.workspace + -var-file=${ws}.tfvarsterraform workspace select -or-create prod
TerragruntOne per “unit” directory terragrunt.hcl,terraform { source = … } pointing to the moduleroot.hcl in remote_state using path_relative_to_include() auto-generated keysinputs = {}, with layering include mergeterragrunt run --all plan
HCP Terraform Stacks (conceptual)Components (.tfcomponent.hcl) + deployments (.tfdeploy.hcl)Managed by HCP Terraform; each deployment has its own independent statedeployment "prod" { inputs = {} }Runs in HCP Terraform; see the official docs for details

The official docs are direct about CLI workspaces: they suit “multiple temporary copies of the same configuration” (for example, spinning up a test environment for a feature branch),not suitable for environment isolation that requires different credentials or different access controls, because all workspaces share the same backend configuration and the same set of credentials.

Monorepo vs. polyrepo

MonorepoPolyrepoModule repo + instance repo (a common compromise)
Code reuserelative paths ../../modules/x, changes visible immediatelyreferenced via Git tags / a private registrymodule repo publishes versions; instance repo pins versions
Change impactA single PR can change the module and all environments at once (convenient and dangerous)Upgrades require a PR in each repoUpgrades are explicit version changes that can be rolled out environment by environment
PermissionsCODEOWNERS controls by directoryRepository-level permissions provide natural isolationThe platform team owns the module repo; application teams own the instance repos
CINeeds “change detection” to run only affected directoriesIndependent pipeline per repo; simpleTwo kinds of pipelines: module tests + instance plan/apply
Suited for1–3 teams with strong consistency requirementsLarge organizations with highly autonomous teamsPlatform engineering + multiple product teams

Componentization: split by “change frequency × owner × dependency direction”

The myapp in this lesson uses three layers of components, deployed bottom-up, with dependencies pointing only downward:

  • 10-network: VNet/VPC, subnets, NAT, private DNS (local lab: Docker network). Owned by the network team; changes infrequently.
  • 20-platform: databases, cache, key vault, container platform (local: Redis container). Owned by the platform team.
  • 30-app: application services, load balancers, DNS records (local: myapp container + nginx). Owned by the application team; changes most frequently.

When: how to choose

  • If environments need different accounts / subscriptions / credentials → use per-environment directories (or Terragrunt), not workspaces.
  • If you need short-lived temporary environments (PR previews) → workspaces are a good fit, combined with terraform.workspace suffixes added to resource names.
  • With many environments × regions × components (for example, 4 environments × 3 regions × 10 components = 120 states), repeated backend/provider code becomes hard to maintain → consider Terragrunt or HCP Terraform Stacks.
  • Small team, few components → plain Terraform with per-environment directories + shared backend.s3.hcl, with the simplest toolchain.
Common misconceptions (1) “A workspace is an environment” — CLI workspaces share backend configuration and credentials; choosing the wrong workspace apply will directly affect prod; HCP Terraform's “workspace” is a different concept (an independent state + variables + permission unit), so don't confuse them. (2) “Per-environment directories = copy and paste” — a directory should contain only about a dozen lines: backend key, provider, one module call and its arguments; the real resource code lives in the module. (3) “Terragrunt is obsolete” — Terragrunt is still actively released in 2026 (v1.2.2, 2026-11-11), and 1.x offers a compatibility promise; whether to adopt it depends on scale, not trends.

Architecture diagram: myapp-infra monorepo layout and 9 states

modules/ (reusable, versioned) network redis web-service myapp-stack (composition module)Only does “wiring”, does not directlydeclare underlying resources live/ (thin root modules: backend + provider + one module call) devstageprod 30-appdev/30-app/…tfstate 30-appstage/30-app/… 30-appprod/30-app/… 20-platformdev/20-platform/… 20-platformstage/20-platform/… 20-platformprod/20-platform/… 10-networkdev/10-network/… 10-networkstage/10-network/… 10-networkprod/10-network/… Arrows = upper layers read outputs from lower layers (dependencies only point downward); dashed lines = module references via source
Figure 1-1: each cell = 1 root module directory = 1 state key = 1 approval and lock unit

Flowchart: the same plan command, and how it locates state under the three layouts

Per-environment directories-chdir=live/prod/30-app init: backend.tf key + backend.s3.hclmerged into the full backend configuration and written to .terraform/ GET s3://tfstate/prod/30-app/terraform.tfstateLock: PUT …/terraform.tfstate.tflock (If-None-Match) CLI workspaceworkspace select prod .terraform/environment = "prod"Same backend, same credentials GET s3://tfstate/env:/prod/app/terraform.tfstateWrong workspace = wrong environment changed Terragruntcd live/prod/app; terragrunt plan Read terragrunt.hcl → include root.hclGenerate backend.tf, download source to the cache directory key = path_relative_to_include()= prod/app/terraform.tfstate, then invoke terraform
Figure 1-2: the essential difference among the three approaches is “who decides the state path, and when”

Interactive simulation: choose a layout and environment, and observe the state paths that init/plan actually read and write

Choose a layout and target environment, then click “Play”. The animation steps through what Terraform (or Terragrunt) does during init — merging the backend configuration, computing the state key, acquiring the lock, and during plan — which object it reads. The final step shows the risk of this layout in a “mistaken operation” scenario.

Select parameters, then click Play.
$

Layout selector: answer 5 questions

Core commands and arguments

CommandPurposeKey arguments / notes
terraform -chdir=DIR <cmd>Runs in the specified root module directory; no need to cdCommonly used in CI; relative paths are based on DIR
terraform init -backend-config=FILEpartial backend configurationcan be used multiple times; or -backend-config="key=dev/app/terraform.tfstate"
terraform init -reconfigurere-initialize, ignoring the existing backend configurationUse when switching keys without migrating state
terraform init -migrate-stateMigrate existing state to a new backend/keyUse when adjusting the layout; back up first
terraform workspace list/select/new/deleteCLI workspace managementselect -or-create (1.4+)
terragrunt run --all planRun plan for all units in the directory tree in dependency order--non-interactive; --queue-include-dir and other filter arguments: see the official docs
terragrunt dag graphOutput the unit dependency graphCommand names follow the terragrunt --help as the source of truth
# Per-environment directories: same module, two states
cd ~/myapp-infra
terraform -chdir=live/dev/10-network init -backend-config=../../backend.s3.hcl
terraform -chdir=live/dev/10-network plan -out=dev.tfplan
Initializing the backend...
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Installing kreuzwerker/docker v4.7.0...
Terraform has been successfully initialized!
...
Plan: 1 to add, 0 to change, 0 to destroy.

How to verify:cat live/dev/10-network/.terraform/terraform.tfstate | grep '"key"' You can see the merged key. Common error:-backend-config The path is relative to -chdir the directory after it, not the current shell directory. Production use: In the CI matrix, each job only needs to pass DIR.

State path of CLI workspaces

mkdir -p /tmp/ws-demo && cd /tmp/ws-demo
cat > main.tf <<'EOF'
terraform {
  backend "s3" { key = "ws-demo/terraform.tfstate" }
  required_providers { random = { source = "hashicorp/random", version = "~> 3.9" } }
}
resource "random_pet" "name" { prefix = terraform.workspace }
output "name" { value = random_pet.name.id }
EOF
terraform init -backend-config=$HOME/myapp-infra/live/backend.s3.hcl
terraform apply -auto-approve
terraform workspace new stage && terraform apply -auto-approve
docker run --rm --network tf-lab -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION=us-east-1 \
  amazon/aws-cli --endpoint-url http://tf-minio:9000 s3 ls s3://tfstate --recursive | grep ws-demo
2026-11-15 10:02:11        812 env:/stage/ws-demo/terraform.tfstate
2026-11-15 10:01:40        815 ws-demo/terraform.tfstate

The default workspace uses key, other workspaces are stored under env:/<name>/ prefix — they share the same bucket and the same credentials. Cleanup: terraform destroy -auto-approve; terraform workspace select default; terraform destroy -auto-approve; terraform workspace delete stage.

Terragrunt (v1.2.2) minimal example

# live/root.hcl — root configuration (name it root.hcl, not terragrunt.hcl in the root directory)
remote_state {
  backend = "s3"
  generate = { path = "backend.tf", if_exists = "overwrite_terragrunt" }
  config = {
    bucket         = "tfstate"
    key            = "${path_relative_to_include()}/terraform.tfstate"
    region         = "us-east-1"
    use_lockfile   = true
    # MinIO labs also need the endpoints / use_path_style / skip_* arguments, the same as backend.s3.hcl
  }
}

# live/prod/30-app/terragrunt.hcl — one unit
include "root" { path = find_in_parent_folders("root.hcl") }
terraform { source = "../../../modules/web-service" }
dependency "platform" {
  config_path = "../20-platform"
  mock_outputs = { redis_host = "redis-mock" }
  mock_outputs_allowed_terraform_commands = ["plan", "validate"]
}
inputs = {
  env        = "prod"
  replicas   = 3
  redis_host = dependency.platform.outputs.redis_host
}
cd live/prod && terragrunt run --all plan

Note: The old terragrunt run-all has been superseded by terragrunt run --all ; the dependency block lets Terragrunt automatically order runs by dependency and execute behind the scenes terraform output -json to read outputs from lower layers. mock_outputs Should only be used in plan/validate; otherwise a mock value could be applied to real resources.

Lab 1: the same network module, deploying the dev and stage directories (about 6 minutes)

Write the network module (Module 2 will further refine the interface):
terraform {
  required_version = ">= 1.11"
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}

variable "env"    { type = string }
variable "subnet" { type = string }

resource "docker_network" "this" {
  name   = "myapp-${var.env}"
  driver = "bridge"
  ipam_config { subnet = var.subnet }
  labels {
    label = "managed-by"
    value = "terraform"
  }
  labels {
    label = "env"
    value = var.env
  }
}

output "network_name" { value = docker_network.this.name }
output "network_id"   { value = docker_network.this.id }
output "subnet"       { value = var.subnet }
Write the thin root module for dev:
cd ~/myapp-infra
for env in dev stage prod; do
  case $env in dev) n=1;; stage) n=2;; prod) n=3;; esac
  cat > live/$env/10-network/main.tf <<EOF
terraform {
  backend "s3" { key = "$env/10-network/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}

module "network" {
  source = "../../../modules/network"
  env    = "$env"
  subnet = "172.30.$n.0/24"
}

output "network_name" { value = module.network.network_name }
output "network_id"   { value = module.network.network_id }
output "subnet"       { value = module.network.subnet }
EOF
done
cat live/stage/10-network/main.tf | head -4
terraform {
  backend "s3" { key = "stage/10-network/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
Deploy dev and stage:
for env in dev stage; do
  terraform -chdir=live/$env/10-network init -input=false -backend-config=../../backend.s3.hcl
  terraform -chdir=live/$env/10-network apply -auto-approve -input=false
done
docker network ls --filter label=managed-by=terraform
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
network_id = "8b1c3f0e9d2a…"
network_name = "myapp-dev"
subnet = "172.30.1.0/24"
...
NETWORK ID     NAME          DRIVER    SCOPE
8b1c3f0e9d2a   myapp-dev     bridge    local
f04a77c1b6e3   myapp-stage   bridge    local
Verify state location and isolation:
docker run --rm --network tf-lab -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION=us-east-1 \
  amazon/aws-cli --endpoint-url http://tf-minio:9000 s3 ls s3://tfstate --recursive
terraform -chdir=live/dev/10-network state list
2026-11-15 10:12:03       1534 dev/10-network/terraform.tfstate
2026-11-15 10:12:15       1540 stage/10-network/terraform.tfstate
module.network.docker_network.this

The two states are fully independent: running destroy in the dev directory cannot affect stage — this is “the directory is the boundary”. The prod directory has been generated but not deployed yet; it is reserved for the capstone lab.

Experience injecting a difference: change stage's subnet to 172.30.20.0/24, run terraform -chdir=live/stage/10-network plan, observe docker_network because ipam_config change requires replacement (-/+, forces replacement). Change it back to the original value. This shows that for networking resources that many things depend on, a single replacement ripples through every container above it — which is exactly why they belong in their own state.
Keep resources: the dev/stage networks created in this lab continue to be used in Module 3. To clean up: terraform -chdir=live/stage/10-network destroy -auto-approve.

Case 1: wrong workspace selected, prod overwritten by dev parameters

Problem: A team used CLI workspaces to tell dev and prod apart, and selected variable files by -var-file=$(terraform workspace show).tfvars concatenation. An engineer stayed on the prod workspace locally and ran an apply with dev instance sizing; the prod database was scaled down and restarted. Approach: Migrated to per-environment directories with a separate AWS account per environment; credentials are bound per directory through the OIDC roles from Lesson 5; applying to prod locally is prohibited (only the pipeline role has write permissions). Configuration: Use terraform init -migrate-state to move each env:/prod/… to the new prod/… key, and in the prod root module add a check block to assert the account ID. Limitation: A change freeze window is needed during migration.

Case 2: monorepo + CODEOWNERS for layered approval

Problem: The platform team and 6 application teams share one repository; anyone can change the VPC. Approach:.github/CODEOWNERS in live/*/10-network/ @org/network-team,modules/ @org/platform-team; CI runs plan only for changed directories (by git diff --name-only mapping to state directories; a module change expands to all directories that reference it). Limitation: The calculation of “module change → which directories are affected” must be reliable, otherwise plans get missed; you can rely on terraform-config-inspect or Terragrunt's dependency graph.

Case 3: introducing Terragrunt after scaling up

Problem: 4 environments × 3 regions × 12 components, 144 root directories in total; each directory copied the provider/backend boilerplate, so changing a provider version constraint means editing 144 places. Approach: Introduce Terragrunt,root.hcl generate the backend and provider uniformly, with region/environment-level region.hcl,env.hcl passed via read_terragrunt_config injection; dependency block replaces handwritten remote_state. Limitations: an extra layer of tooling and cache directories (.terragrunt-cache), and when troubleshooting you need to know where the Terraform code actually runs; the team must standardize the Terragrunt version (can be pinned using terragrunt_version_constraint). An alternative is that since Terraform 1.17, provider requirements can use variables and locals, and with the module source variables from 1.15, some boilerplate is reduced, but the backend still needs partial configuration.

Common errors and fixes

Error: Variables not allowed ... on main.tf line 3, in terraform: backend "s3" { key = var.key }

Cause: The backend block is loaded before variable evaluation and cannot reference var/local.

terraform init -backend-config="key=dev/30-app/terraform.tfstate" -backend-config=../../backend.s3.hcl

Fix: Use partial configuration, or generate backend.tf with Terragrunt.

Error: Backend configuration changed ... A change in the backend configuration has been detected, which may require migrating existing state.

Cause:.terraform/terraform.tfstate The recorded backend arguments differ from the current configuration (for example, the key or endpoint was changed).

Fix: To move the state to a new location: terraform init -migrate-state; if only the local cache is stale and the remote is unchanged: terraform init -reconfigure. First confirm which option you want; -reconfigure using the wrong one makes Terraform point to an empty state, and the next plan will show “everything to be created”.

Plan: 37 to add, 0 to change, 0 to destroy. (even though the resources already exist)

Cause: Pointing to the wrong or empty state: wrong workspace selected, misspelled key,-reconfigure or the state was moved to a new key.

terraform workspace show
grep -A3 '"config"' .terraform/terraform.tfstate | head
terraform state list | head

Fix: Stop immediately; do not apply. Verify the key and workspace; add check or precondition to verify that the current account/subscription matches the expected one.

terragrunt: Error reading file at path …/root.hcl: no such file / Could not find a root.hcl in any of the parent folders

Cause:find_in_parent_folders("root.hcl") The root configuration cannot be found; or the old project named the root configuration terragrunt.hcl.

Fix: Rename the root file to root.hcl and update all includes; do not also place a terragrunt.hcl, otherwise run --all will treat it as a unit.

Error: Error acquiring the state lock ... PreconditionFailed: At least one of the pre-conditions you specified did not hold

Cause: S3 native lock: another process already holds .tflock; or a lock file was left behind by a previous process crash.

terraform force-unlock LOCK_ID   # run only after confirming no other process is running

Fix: First confirm the lock holder (the error message contains Who/Created); in CI, set a concurrency group for each state directory to avoid parallel runs in the same directory.

Command-line questions
1. Without changing directory, initialize using the shared backend file live/prod/20-platform, and set the state key to prod/20-platform/terraform.tfstate.
terraform -chdir=live/prod/20-platform init \
  -backend-config=../../backend.s3.hcl \
  -backend-config="key=prod/20-platform/terraform.tfstate"
2. Move the state managed via workspace prod to a new key in the per-directory layout.
cd old-app && terraform workspace select prod
terraform state pull > prod-backup.tfstate         # back up first
cd ../live/prod/30-app
terraform init -backend-config=../../backend.s3.hcl
terraform state push ../../../old-app/prod-backup.tfstate   # target state must be empty
terraform plan    # expected: No changes (if addresses differ, combine with a moved block)
Scenario analysis questions
A startup team (5 people, 1 product, single AWS account) asks you: should they adopt Terragrunt and multiple repos? What is your recommendation and reasoning?

Not recommended from the start. Recommended: monorepo + per-environment directories + three-layer components + shared backend.s3.hcl; at minimum, put prod in a separate account (AWS Organizations is free) and use OIDC roles to separate dev/prod credentials. Only when the combinations of components × environments × regions become so numerous that boilerplate is hard to maintain (dozens of root directories or more), or when cross-team autonomy is needed, introduce Terragrunt or HCP Terraform Stacks. First use conventions (naming, directories, keys) to draw the boundaries correctly; that matters more than the choice of tool.

Verified instructional videos

▶
How To Structure Terraform Project (3 Levels) — Anton Putra
English · explains project structure at three levels — from a single directory, to per-environment directories, to Terragrunt — directly corresponding to the layout comparison in this module (for the Terragrunt CLI, follow the v1.x docs)
▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · the “multiple environments: workspace vs file structure” section is a good supplement to this module

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3; storyboards and narration scripts are provided and can be handed to a video tool.

Shot 1 · 0–20s
Visual: a huge main.tf file stuffed with VPC, database, and application; a red apply button is pressed and all resources flash at once.
Narration: one directory managing everything means a single mistake can affect everything.
Shot 2 · 20–45s
Visual: the grid expands into three columns (dev/stage/prod) and three rows (network/platform/application), with each cell labeled with its state key.
Narration: per-environment directories turn each cell into its own root module, state, lock, and approval.
Shot 3 · 45–70s
Visual: same directory; the workspace dropdown switches from dev to prod, the S3 path becomes env:/prod/…, but the key (credentials) stays the same one.
Narration: a workspace only adds a prefix to the state path; credentials and backend are shared, so it is not suitable for isolating production.
Shot 4 · 70–90s
Visual: the Terragrunt icon sits above the directory tree, automatically generates backend.tf, and runs units in order following the dependency arrows.
Narration: as scale grows, an orchestration layer like Terragrunt can eliminate boilerplate and run all units in dependency order.
or score ≥ 70% in the “Quiz”

Module 2 · Module Composition and Interface Design

07:00 – 16:00 · A module is an API: inputs are contracts, outputs are promises, and version numbers are respect for callers
9 mindeprecated attribute 1.15 · import inside modules 1.16★★★★★
Learning objectives
  • Distinguish three kinds of modules: root modules (thin; only backend/provider/arguments),composition modules (only wiring),resource modules / leaf modules (best practice for encapsulating one type of resource).
  • Use dependency injection to design interfaces: a module receives network_id,subnet_ids rather than creating them internally or “guessing” them with data sources; the provider is passed in by the caller.
  • Write robust interfaces: type constraints,optional() defaults,validation,nullable = false, output types (1.15),deprecated (1.15), and publish modules with SemVer.
Prerequisites: module blocks,for_each variables/outputs. Importance:★★★★★

What: three layers of modules

TypeResponsibilityCan containShould not containExample in myapp
Root module (root)Decides “where, with what credentials, using which version, and which parameters to pass”backend, provider, one or a few module calls, remote_state / data source readsMany resource blocks, complex logiclive/prod/30-app/main.tf
Composition module (composition)“Wires” multiple resource modules into one capabilitymodule calls, a few glue resources (such as DNS records)provider blocks, backend, environment checks (if env == "prod")modules/myapp-stack
Resource module (leaf)Encapsulates one type of resource and its secure defaultsresource, local data, validationprovider blocks, cross-domain resources (creating a database inside the network module)modules/network,redis,web-service

Why: the cost of “god modules”

A “god module” is a module that uses dozens of toggle variables (create_vpc,enable_redis,use_existing_db…) and many count = var.x ? 1 : 0 blocks that try to cover every scenario. Symptoms:

  • Any change requires regression testing of all callers; version numbers lose meaning (every release is a breaking change).
  • Resource addresses are full of [0], so flipping a toggle causes destroy/create.
  • A single plan spans multiple domains, so reviewers cannot judge risk; permission boundaries cannot be split.

How: seven rules for interface design

  1. Dependency injection: Ask for exactly what you need. web-service If it needs a network, it accepts network_name; if it needs Redis, it accepts redis_host. Whether to create a new network is the caller's decision. The official module composition docs call this “dependency inversion”.
  2. Provider is passed in by the caller: The child module only declares required_providers (when multiple providers are needed, use configuration_aliases), and does not write provider blocks — a module with a provider block cannot use count/for_each/depends_on.
  3. Strong types + defaults: Use object({ … optional(x, default) }) to bundle a group of related parameters and avoid 30 flat variables; nullable = false let a null input fall back to the default value.
  4. Fail early:validation Validate formats (images must include a tag, replica count range, valid CIDR); since 1.9, validation can reference other variables.
  5. Outputs are promises: Only output the stable identifiers the caller needs (IDs, names, endpoints); since 1.15, an output can declare type, preventing accidental type changes.
  6. Evolve without breaking: When changing resource addresses, use moved blocks; to retire variables/outputs, use the 1.15 deprecated = "…" attribute to warn for one major version first, then remove.
  7. SemVer: patch (bug fixes, no plan changes) → minor (new optional inputs/outputs) → major (removing/renaming inputs, or default changes that cause resource replacement).

When: when is a module worth writing

  • The same resource combination appears in two or more places and should stay consistent (for example, “a service with health checks”).
  • Organization-level security defaults must be enforced (encryption, tags, logging).
  • Do not wrap a single resource in a “pass-through module” (one that simply exposes the resource's arguments as-is) — it only adds maintenance cost.

Comparison with similar technologies

Terraform modulesTerragrunt unitPulumi ComponentHelm Chart (analogy)
Interfacevariables / outputsinputs / dependency outputsclass constructor parameters / propertiesvalues.yaml
VersionGit ref / registry versionref in sourcelanguage package managerChart version
Compositionmodule calling module (same state)cross-state between unitscomponent nestingsub-chart
Common misconceptions (1) “The more generic a module, the better” — generality comes from composition, not toggles. (2) “A composition module can contain provider” — this makes the module unable to be for_each, and also prevents resources from being destroyed correctly when the module is removed (the provider configuration disappears with the module). (3) “Looking up the VPC with a data source inside the module is more convenient” — this hides an implicit “lookup by name” dependency inside the module; if the name changes or two objects share the same name, it silently picks the wrong one; passing the ID as an input is more explicit. (4) “ref=main also counts as a version” — branches move, so production must pin a tag or commit.

Architecture diagram: thin root module → composition module → resource module

live/preview/main.tf (root) backend "s3" + provider "docker"module "stack" { env = "pr-123" }≈ 20 lines modules/myapp-stack (composition) module network / redis / web-serviceConnect A's outputs to B's inputsNo provider blocks, no environment checks networkin: env, subnetres: docker_networkout: network_name ─────────┐ redisin: env, network_name ◀─res: image, volume, containerout: host, port ─────────┐ web-servicein: network_name, redis_host ◀─res: app × N, nginx LBout: url, app_names Leaf modules do not reference each other: all dependencies are explicitly injected by the composition module (or the root module)
Figure 2-1 Dependency injection: leaf modules only declare “what I need”; the upper layer decides “where it comes from”

Comparison: god module vs. composition

God module modules/everything variable "create_network" {} variable "enable_redis" {} variable "use_existing_network_id" {} … 47 variables in total resource "docker_network" "this" { count = var.create_network ? 1 : 0 } local.net = var.create_network ? docker_network.this[0].name : var.existing ✗ Every release may be a breaking change✗ Toggle flip = resource destroy/create✗ All domains in the same review Small modules + composition “Existing network” = the caller does not call the network module and passes network_name directly “No Redis” = do not call the redis module 3–8 variables per module, independently versioned ✓ Changes are localized; SemVer is meaningful✓ Stable resource addresses, no [0]✓ Owners and state can be split by domain
Figure 2-2: “conditional creation” should move up to “whether to call the module”, rather than sink into a toggle inside the module

Interactive demo: how far does one change propagate through the dependency graph?

Terraform core parses the configuration into a resource dependency graph (DAG,terraform graph exportable): every reference a.b.c is an edge. During plan, core calls the provider's PlanResourceChange, and changes propagate downstream along the edges (unknown values (known after apply) can make downstream resources also become “update/replace needed”). Select a module design and a change, and observe the number of affected nodes and the scope that needs review.

Select a design and a change, then play.
$ terraform plan

Core commands and syntax

Command / syntaxPurposeNotes
terraform get -updateRe-download modulesNeeded after changing source or ref — needed; init -upgrade also updates
terraform graph -type=planOutput DOT dependency graph| dot -Tsvg > g.svg
terraform consoleInteractive evaluationDebugging for expressions,optional() defaults
terraform validateStatic checks (including the constant parts of validation rules)Must run in module repo CI
terraform testModule unit/integration tests (*.tftest.hcl)Since 1.17, mock_provider supports ephemeral resources
source = "git::https://…/modules.git//web-service?ref=v1.3.0"Reference a specific tag from a Git subdirectory// the part after it is the subdirectory
source = "app.terraform.io/org/web-service/docker" + version = "~> 1.3"Private registry + version constraintsOnly supported for registry sources version Argument

Writing robust interfaces

variable "env" {
  type        = string
  description = "Environment name, used for resource naming"
  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{1,15}$", var.env))
    error_message = "env may only contain lowercase letters, digits, and hyphens; length 2–16."
  }
}

variable "network_name" {
  type        = string
  description = "Injected: the Docker network the container should join (provided by the network module or an existing network)"
}

variable "image" {
  type = string
  validation {
    condition     = can(regex(":[^:]+$", var.image)) && !endswith(var.image, ":latest")
    error_message = "image must include an explicit tag, and cannot be latest."
  }
}

variable "replicas" {
  type     = number
  default  = 2
  nullable = false
  validation {
    condition     = var.replicas >= 1 && var.replicas <= 10
    error_message = "replicas must be between 1–10."
  }
}

variable "redis" {
  description = "Injected: Redis connection information"
  type = object({
    host = string
    port = optional(number, 6379)
  })
}

variable "http_port" {
  type    = number
  default = null   # null = do not publish ports to the host
}

variable "color" {
  type    = string
  default = "none"
}

variable "app_port" {
  type       = number
  default    = 5000
  deprecated = "app_port will be removed in v2.0.0: myapp always listens on 5000."   # Terraform 1.15+
}

How to verify: Passing image = "myapp:latest" then terraform plan will report a validation error before planning. Common mistake: Referencing resource attributes in validation (you can only reference variables; since 1.9 you can reference other variables and locals). Production use: Use validation to turn team conventions (naming, tags, banning latest) into machine checks. deprecated The attribute requires Terraform 1.15+; if the module must still support older CLIs, declare it in required_version .

Multi-provider modules: configuration_aliases

# Child module: declares that two aws configurations are needed
terraform {
  required_providers {
    aws = {
      source                = "hashicorp/aws"
      version               = "~> 6.0"
      configuration_aliases = [aws.primary, aws.dr]
    }
  }
}
resource "aws_s3_bucket" "primary" { provider = aws.primary  bucket = "${var.name}-primary" }
resource "aws_s3_bucket" "dr"      { provider = aws.dr       bucket = "${var.name}-dr" }

# Caller: pass explicitly
module "replicated_bucket" {
  source    = "../modules/replicated-bucket"
  name      = "myapp-prod-assets"
  providers = { aws.primary = aws.cac1, aws.dr = aws.use1 }
}

Publish module versions

cd ~/myapp-modules         # if using “module repo + instance repo”
git tag -a v1.3.0 -m "web-service: add optional color input"
git push origin v1.3.0
# Caller upgrade (roll out environment by environment: dev → stage → prod)
sed -i 's/?ref=v1.2.1/?ref=v1.3.0/' live/dev/30-app/main.tf
terraform -chdir=live/dev/30-app init -upgrade && terraform -chdir=live/dev/30-app plan

Lab 2: write the redis / web-service modules and use a composition module to bring up a “preview environment” (about 8 minutes)

redis module:
terraform {
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}

variable "env"          { type = string }
variable "network_name" { type = string }
variable "image" {
  type    = string
  default = "redis:7-alpine"
}

resource "docker_image" "redis" {
  name         = var.image
  keep_locally = true
}

resource "docker_volume" "data" {
  name = "myapp-${var.env}-redis-data"
}

resource "docker_container" "redis" {
  name    = "myapp-${var.env}-redis"
  image   = docker_image.redis.image_id
  restart = "unless-stopped"
  command = ["redis-server", "--appendonly", "yes"]
  networks_advanced {
    name = var.network_name
  }
  volumes {
    volume_name    = docker_volume.data.name
    container_path = "/data"
  }
  healthcheck {
    test     = ["CMD", "redis-cli", "ping"]
    interval = "5s"
    timeout  = "2s"
    retries  = 5
  }
  wait = true
}

output "host" {
  value = docker_container.redis.name   # in a user-defined network, the container name is the DNS name
}
output "port" {
  value = 6379
}
web-service module (use variables.tf from the “Commands” page for the variables; the main body is as follows):
terraform {
  required_version = ">= 1.15"
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}

locals {
  name  = "myapp-${var.env}"
  alias = "myapp-${var.env}-app"
  nginx_conf = <<-EOT
    server {
      listen 80;
      resolver 127.0.0.11 valid=5s ipv6=off;   # Docker built-in DNS, re-resolved every 5 seconds
      set $upstream http://${local.alias}:5000;
      location / {
        proxy_pass $upstream;
        proxy_next_upstream error timeout http_502;
      }
      location = /lb-health { return 200 "ok\n"; }
    }
  EOT
}

resource "docker_image" "app" {
  name         = var.image
  keep_locally = true
}

resource "docker_image" "nginx" {
  name         = "nginx:1.29-alpine"
  keep_locally = true
}

resource "docker_container" "app" {
  count   = var.replicas
  name    = "${local.name}-app-${count.index}"
  image   = docker_image.app.image_id
  restart = "unless-stopped"
  env = [
    "APP_ENV=${var.env}",
    "APP_COLOR=${var.color}",
    "REDIS_HOST=${var.redis.host}",
    "REDIS_PORT=${var.redis.port}",
  ]
  networks_advanced {
    name    = var.network_name
    aliases = [local.alias]           # all replicas share one DNS name → Docker DNS round-robin
  }
  healthcheck {
    test         = ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:5000/healthz')"]
    interval     = "5s"
    timeout      = "2s"
    retries      = 3
    start_period = "5s"
  }
  wait         = true                 # creation succeeds only after the container is healthy
  wait_timeout = 60
}

resource "docker_container" "lb" {
  count   = var.http_port == null ? 0 : 1
  name    = "${local.name}-lb"
  image   = docker_image.nginx.image_id
  restart = "unless-stopped"
  networks_advanced { name = var.network_name }
  ports {
    internal = 80
    external = var.http_port
  }
  upload {
    file    = "/etc/nginx/conf.d/default.conf"
    content = local.nginx_conf
  }
  depends_on = [docker_container.app]
}

output "url" {
  value = var.http_port == null ? null : "http://localhost:${var.http_port}"
}
output "app_names" {
  type  = list(string)                # Terraform 1.15+: output type constraint
  value = docker_container.app[*].name
}

Note: nginx_conf in $upstream is an nginx variable (no braces; Terraform does not interpolate it),${local.alias} is Terraform interpolation. Using the variable form proxy_pass is so nginx re-resolves resolver DNS periodically; Module 6's blue/green switching depends on this.

Composition module: only wiring, no provider:
terraform {
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}

variable "env"       { type = string }
variable "subnet"    { type = string }
variable "image"     { type = string }
variable "replicas"  {
  type    = number
  default = 1
}
variable "http_port" { type = number }

module "network" {
  source = "../network"
  env    = var.env
  subnet = var.subnet
}

module "redis" {
  source       = "../redis"
  env          = var.env
  network_name = module.network.network_name
}

module "app" {
  source       = "../web-service"
  env          = var.env
  network_name = module.network.network_name
  image        = var.image
  replicas     = var.replicas
  http_port    = var.http_port
  redis        = { host = module.redis.host, port = module.redis.port }
}

output "url" { value = module.app.url }
Use a workspace to spin up a PR preview environment (exactly the “temporary copy” scenario workspaces are good at):
mkdir -p ~/myapp-infra/live/preview && cd ~/myapp-infra/live/preview
cat > main.tf <<'EOF'
terraform {
  backend "s3" { key = "preview/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}

variable "pr" { type = number }

module "stack" {
  source    = "../../modules/myapp-stack"
  env       = "pr-${var.pr}"
  subnet    = "172.31.${var.pr % 250}.0/24"
  image     = "myapp:1.0"
  http_port = 18000 + var.pr % 1000
}
output "url" { value = module.stack.url }
EOF
terraform init -backend-config=../backend.s3.hcl
terraform workspace select -or-create pr-123
terraform apply -auto-approve -var pr=123
curl -s localhost:18123/; curl -s localhost:18123/
Apply complete! Resources: 8 added, 0 changed, 0 destroyed.
Outputs:
url = "http://localhost:18123"
myapp v1.0 env=pr-123 color=none host=4f1d2a7c9b10 hits=1
myapp v1.0 env=pr-123 color=none host=4f1d2a7c9b10 hits=2
Verify interface validation:
terraform plan -var pr=123 -var 'dummy=1' 2>&1 | head -3   # undeclared variable → error
sed -i 's/myapp:1.0/myapp:latest/' main.tf && terraform plan -var pr=123 2>&1 | grep -A2 "Invalid value"
sed -i 's/myapp:latest/myapp:1.0/' main.tf
│ Error: Invalid value for variable
│   on ../../modules/myapp-stack/main.tf line 29, in module "app":
│ image must include an explicit tag, and cannot be latest.
Clean up the preview environment (run by the pipeline when the PR is closed):
terraform destroy -auto-approve -var pr=123
terraform workspace select default && terraform workspace delete pr-123

Case 1: breaking down a 3,000-line god module

Problem: The “platform” module contains VPC, EKS, RDS, Redis, and IAM, with 61 variables in total; a release adding a parameter to RDS caused VPC replacement in the plans of 3 teams (a default value changed as a result). Approach: Split by domain into 5 resource modules + 1 composition module (keep the original interface as a transition), and in the composition module use moved { from = module.platform.aws_db_instance.this[0] to = module.db.aws_db_instance.this } blocks to move addresses; ensure the plan has zero changes, then release v2.0.0. Limitation: Cross-module moved blocks only work within the same state; splitting the state requires removed + import (Modules 3 and 7).

Case 2: using validation to eliminate a class of incidents

Problem: Someone passed replicas = 0 into prod, taking the service offline. Approach: Add validation (1–10) to the web-service module; add cross-variable validation in the prod root module (1.9+) condition = var.env != "prod" || var.replicas >= 2. Limitation: Validation only checks inputs; it cannot prevent manual changes to cloud resources — that belongs to drift detection (Lesson 5).

Case 3: module registry and upgrade cadence

Problem: 40 repositories reference ref=main, and a single module change made every nightly plan over the weekend show differences. Approach: Switch everything to tags; use Renovate/Dependabot to automatically open PRs for module tags; module repo CI runs terraform test and generates a CHANGELOG. Configuration: Private registry (HCP Terraform / Terraform Enterprise / GitLab, etc.) together with version = "~> 1.4" that only accept minor-version upgrades. Limitations:~> Only valid for registry sources; Git sources can only hardcode a ref. Since 1.15, source/version can use variables and locals, but be careful: “which version is actually used” is no longer visible at a glance in the code.

Common errors and fixes

Error: Module is incompatible with count, for_each, and depends_on ... The module at module.x is a legacy module which contains its own local provider configurations

Cause: A child module contains a provider block.

Fix: Delete the provider block from the child module, and keep only required_providers (if necessary, configuration_aliases), passed in by the root module.

Error: Provider configuration not present ... To work with module.app.docker_container.app its original provider configuration at module.app.provider["registry.terraform.io/kreuzwerker/docker"] is required, but it has been removed.

Cause: A module that carries its own provider block was deleted; Terraform can no longer use that provider configuration to destroy the resources inside it.

Fix: Temporarily restore the module (or its provider block) → first run terraform destroy -target=module.app → then delete the module code. Long term: do not write provider blocks in modules.

Error: Unsupported argument ... An argument named "redis_host" is not expected here.

Cause: The module interface had a breaking change (for example, redis_host changed to an object redis), but callers upgraded the module version without updating their calls.

Fix: Adjust calls according to the module CHANGELOG; module authors should first go through deprecated for one transitional major version, and reflect breaking changes in the major version number.

Error: Invalid count argument ... The "count" value depends on resource attributes that cannot be determined until apply

Cause:count/for_each Depends on a value that is only known after apply (such as another resource's ID); this is common when conditional creation is written inside the module: count = var.network_id == null ? 1 : 0 while network_id comes from a resource created in the same apply.

Fix: Use a static boolean known to the caller (create_x = true), or change it to “whether to call the module”; do not use whether an ID is null to decide count.

Warning: Deprecated variable ... The variable "app_port" is deprecated: app_port will be removed in v2.0.0

Cause: The caller passed a value to a variable marked deprecated since 1.15. This is the expected warning.

Fix: Remove that argument. If CI uses an older Terraform version, it will report Unsupported argument "deprecated": upgrade to 1.15+, or in the module required_version to give a clear error.

Command-line questions
1. Export live/preview dependency graph and render it as SVG.
terraform -chdir=live/preview graph -type=plan | dot -Tsvg > preview-graph.svg
2. List only the resource addresses managed by the web-service child module in the preview environment, and check the port the nginx container records in state.
terraform -chdir=live/preview state list module.stack.module.app
terraform -chdir=live/preview state show 'module.stack.module.app.docker_container.lb[0]' | grep -A3 ports

Address nesting rule: module.<composition>.module.<leaf>.<type>.<name>[index]. Addresses with square brackets must be quoted in the shell.

Scenario analysis questions
A team wants to write a modules/app, using var.env == "prod" ? 3 : 1 to decide the replica count,var.env == "prod" ? "Premium" : "Basic" to decide the SKU. Please review this design.

Not recommended: putting environment checks inside the module. It hard-codes “environment policy” into a reusable component; adding a “perf” environment requires changing the module and releasing a new version, and dev never tests the prod configuration path. Instead, pass replicas,sku as inputs (with defaults and validation), explicitly passed in by each environment's root module (or tfvars); if needed, create an “environment configuration” object (locals.env_profiles) placed in the root module or composition layer. A module only answers “how to build it”; the root module answers “what it should look like”.

Verified instructional videos

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · the “Modules” chapter explains module sources, inputs and outputs, and modular project organization
▶
How To Structure Terraform Project (3 Levels) — Anton Putra
English · where modules fit in different project structures

Official docs

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3; storyboards and narration scripts are provided.

Shot 1 · 0–25s
Visual: a control panel full of switches (god module); flip one switch and several spots on the panel light up red.
Narration: a module that uses switches to cover every scenario means any change affects all callers.
Shot 2 · 25–55s
Visual: three LEGO bricks (network, redis, web-service), each with only a few sockets; the composition module uses connectors to plug outputs into inputs.
Narration: small modules only declare what they need, and the composition module handles the wiring — this is dependency injection.
Shot 3 · 55–80s
Visual: a shield icon pops up beside the variable definition, and the invalid input latest is blocked.
Narration: types, optional defaults, and validation rules catch errors before the plan.
Shot 4 · 80–100s
Visual: version numbers v1.2.1 → v1.3.0 → v2.0.0; a “breaking change” label appears at the major version, and environments upgrade one after another.
Narration: release modules with semantic versioning, and upgrade in the order dev, stage, prod.
or score ≥ 70% in the “Quiz”

Module 3 · State Splitting and Cross-Stack References

16:00 – 24:00 · Splitting state balances “blast radius” against “coordination cost”; cross-stack references are the APIs between stacks
8 minremoved block 1.7+ · import block 1.5+★★★★★
Learning objectives
  • Decide state boundaries using five dimensions: “blast radius, change frequency, owner, credentials, and refresh time.”
  • Compare three cross-stack reference methods: terraform_remote_state, tag/name-based data source lookup,parameter store (AWS SSM Parameter Store / Azure App Configuration / HCP Terraform tfe_outputs), and explain the coupling and permission implications of each.
  • Know that terraform_remote_state requires reading the entire state snapshot, so design permissions for “who can read which state”; be able to use removed + import to move resources between states.
Prerequisites: Module 1's directory layout and the S3 backend. Importance:★★★★★

What: blast radius

Blast radius = a single apply the set of resources that can be changed or destroyed in the worst case. It is determined by the state boundary: whatever is in one state, a single mistake (wrong variable, provider bug, accidentally deleting a line of code,-target misuse) can affect. The goal of splitting state is to keep high-risk, rarely changed resources (networking, databases) away from frequently changed ones (applications).

Why: five dimensions of splitting

DimensionSignal to splitConclusion for myapp
Blast radiusHas unrecoverable resources (databases, DNS zones, KMS keys)Platform layer is independent; the database is added prevent_destroy
Change frequencySome resources change daily, others only a few times a yearApplication layer is independent
Owner / approvalOwned by different teams, requires different approversThe network team owns 10-network
CredentialsRequires different permissions (network admin vs. application deployer)One OIDC role per layer (Lesson 5)
Performanceplan refresh takes more than a few minutes, resource count in the thousandsCurrent scale does not need further splitting

Conversely, over-splitting has costs: the more cross-stack references, the harder deployment ordering and version compatibility become (a “distributed monolith”); delivering one feature may require changing 4 states and running 4 pipelines. Rule of thumb: Keep resources that live and die together in the same state (for example, an application plus its dedicated load balancer listener rule),separate resources with different lifecycles and owners.

How: three cross-stack reference methods

terraform_remote_stateData source lookup (by name/tag)Parameter store (SSM / App Configuration / tfe_outputs)
MechanismBuilt-in terraform the provider uses the backend client to read another state snapshot and returns its root module outputscalls cloud APIs to query real resources, such as aws_vpc (filter tag),azurerm_virtual_network,docker_networkThe producer explicitly writes the values to share into the parameter store; the consumer reads them with a data source
CouplingCoupled to the other side's backend type, key, and output namesCoupled to naming/tagging conventionsCoupled to the parameter path (loosest; usable across tools)
Read permissionRequires reading the entire state object (contains all resource attributes, may include secrets)Requires read-only API permission on the corresponding resourceRead only those parameters; can be authorized precisely
Value sourceOutput from the last apply (may be stale)Current live stateLast written value
Non-Terraform consumersNot friendlyPossibleVery friendly (applications, scripts, and Ansible can all read it)
Suitable forStacks within the same team and trust domainResources with stable, unique tags/namesContracts across teams, trust domains, and tools

Permissions to read outputs: why remote_state is “all or nothing”

The official documentation explicitly notes that when using terraform_remote_state , the consumer needs read access to the entire state snapshot, and the state may contain sensitive information (database passwords, private keys, etc.,sensitive only masked in CLI output but still stored in plain text in the state). Therefore, the official recommendation is, where possible, to publish shared data explicitly to a dedicated configuration store. On S3, you can use IAM policies to restrict access to s3:GetObject specific keys (for example, the application-layer role can only read prod/10-network/* and prod/20-platform/*), but you cannot grant access to only certain fields within the state.

When: selection guide

  • Same team, same trust domain, values used only by Terraform → terraform_remote_state (simple), and make sure lower-layer state contains no secrets (Module 5).
  • Cross-team/cross-account, or applications also need to read it → parameter store (SSM /myapp/prod/network/vpc_id, Azure App Configuration key).
  • Only need one ID and the resource has a unique tag → data source lookup; but note that “not found” makes plan fail, and “found two” errors in most data sources too.
  • HCP Terraform users → tfe_outputs data source + the workspace's “remote state sharing” setting, which can expose only outputs.
Common misconceptions① “sensitive = true output is not read by remote_state”—it is read, just masked in display; the value is stored in plain text in state. ② “remote_state is real-time”—it reads the other side's last apply wrote outputs; if the other side changed the code but has not applied, you still read the old value. ③ “Terraform handles dependency order after splitting state”—there is no dependency graph across states; ordering relies on directory conventions, pipeline orchestration, or Terragrunt/Stacks. ④ “Child module outputs can also be read by remote_state”—it returns only root module outputs; to share them, they must be re-exported from the root module.

Architecture diagram: three-layer state and output passing

10-networkdocker_network.myapp-devoutputs: network_name, subnet 20-platformredis container + volumeoutputs: redis_host, redis_port 30-appmyapp × N + nginxoutputs: url MinIO / S3 bucket tfstatedev/10-network/terraform.tfstatedev/20-platform/… · dev/30-app/… network_name redis_host network_name (the application layer also reads the network layer directly) Solid arrows = outputs read by data.terraform_remote_state; dashed lines = each layer writes its state to its own key
Figure 3-1: dependencies may only be read top-down; lower layers never read upper layers, to avoid cycles

Permission diagram: who can read which state object

role/tf-network-prod role/tf-platform-prod role/tf-app-prod prod/10-network/terraform.tfstate prod/20-platform/terraform.tfstate (contains DB info) prod/30-app/terraform.tfstate Read/write Read/write Read/write Read-only access to the entire platform state → can see the DB password? Switch to SSM parameters
Figure 3-2: S3 IAM can only grant access per object (key); field-level least privilege relies on “publishing only the values needed”

Core animation: dependencies and output passing between multi-state stacks

Play terraform -chdir=live/dev/30-app plan the actual process: Terraform core builds the dependency graph → evaluates first data.terraform_remote_state (built-in terraform.io/builtin/terraform provider's ReadDataSource) → reads the lower-layer state with the S3 backend client's GetObject → parses the outputs → substitutes values into module arguments → calls the docker provider's PlanResourceChange. You can switch to the scenario “the network layer changed the output but has not yet been applied” and observe the effect of reading stale values.

Ready.
$ terraform -chdir=live/dev/30-app plan

Core commands and syntax

Command / syntaxPurposeNotes
data "terraform_remote_state" "x" { backend = "s3" config = {…} }Read another state's root outputsResult is in data.terraform_remote_state.x.outputs.<name>; can use defaults = {} to provide a default value for a missing output
terraform output -jsonView this state's outputs (JSON)For script/pipeline consumption; sensitive values are shown in plain text in JSON
terraform state pullDownload the full stateAudit the state for secrets: | jq '.resources[].instances[].attributes'
removed { from = … lifecycle { destroy = false } }Remove from state without destroying (1.7+)Used in the “old stack” when splitting state
import { to = … id = … }Adopt the resource in the “new stack”1.5+; 1.7+ supported for_each
terraform state mv -state=a -state-out=bMove resources between two local state filesFor remote backends, use removed + import

DRY remote_state approach

locals {
  env = "dev"
  state_backend = {
    bucket                      = "tfstate"
    region                      = "us-east-1"
    endpoints                   = { s3 = "http://localhost:9000" }
    use_path_style              = true
    skip_credentials_validation = true
    skip_requesting_account_id  = true
    skip_metadata_api_check     = true
    skip_region_validation      = true
  }
}

data "terraform_remote_state" "network" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "${local.env}/10-network/terraform.tfstate" })
}

data "terraform_remote_state" "platform" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "${local.env}/20-platform/terraform.tfstate" })
  defaults = {
    redis_port = 6379        # fallback when an older platform-layer version does not have this output
  }
}

How to verify:terraform console in data.terraform_remote_state.network.outputs. Common error: A misspelled key does not report “not found”; instead it returns empty outputs, and later references fail with Unsupported attribute. Production use: Put state_backend in a shared location for each layer _shared.tf (can be done with symlinks or generated by Terragrunt).

Alternative A: data source lookup (runs locally)

data "docker_network" "net" {
  name = "myapp-${local.env}"      # look up the real resource by naming convention
}
# Usage: data.docker_network.net.name / .id

Alternative B: parameter store (cloud equivalent code)

# ---- Producer (AWS, 10-network stack) ----
resource "aws_ssm_parameter" "vpc_id" {
  name  = "/myapp/prod/network/vpc_id"
  type  = "String"
  value = aws_vpc.main.id
}
# ---- Consumer (30-app stack) ----
data "aws_ssm_parameter" "vpc_id" {
  name = "/myapp/prod/network/vpc_id"
}
# IAM: the tf-app-prod role only needs ssm:GetParameter on arn:aws:ssm:ca-central-1:<acct>:parameter/myapp/prod/network/*

# ---- Producer (Azure, 10-network stack) ----
resource "azurerm_app_configuration_key" "vnet_id" {
  configuration_store_id = var.app_config_id
  key                    = "myapp:prod:network:vnet_id"
  value                  = azurerm_virtual_network.main.id
}
# ---- Consumer ----
data "azurerm_app_configuration_key" "vnet_id" {
  configuration_store_id = var.app_config_id
  key                    = "myapp:prod:network:vnet_id"
}
# RBAC: the consumer identity only needs the “App Configuration Data Reader” role

Move a resource from one state to another (remote backend)

# 1) Old stack (for example, the original all-in-one): remove without destroying
removed {
  from = module.redis.docker_container.redis
  lifecycle { destroy = false }
}
# 2) New stack (20-platform): adopt
import {
  to = module.redis.docker_container.redis
  id = "<full container ID>"     # docker inspect -f '{{.Id}}' myapp-dev-redis
}

Order: first run in the new stack plan and confirm the plan shows only “import” and no “destroy/create”, then apply; then apply removed in the old stack. Between the two steps the resource exists in both states, so do not make other changes in the old stack during this time.

Lab 3: platform and application layers read lower-layer outputs via remote_state (about 7 minutes)

Platform layer (dev/20-platform): reads the network layer and deploys Redis:
cd ~/myapp-infra/live/dev/20-platform
cat > main.tf <<'EOF'
terraform {
  backend "s3" { key = "dev/20-platform/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}

locals {
  env = "dev"
  state_backend = {
    bucket = "tfstate", region = "us-east-1", endpoints = { s3 = "http://localhost:9000" }
    use_path_style = true, skip_credentials_validation = true, skip_requesting_account_id = true
    skip_metadata_api_check = true, skip_region_validation = true
  }
}

data "terraform_remote_state" "network" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "${local.env}/10-network/terraform.tfstate" })
}

module "redis" {
  source       = "../../../modules/redis"
  env          = local.env
  network_name = data.terraform_remote_state.network.outputs.network_name
}

output "redis_host" { value = module.redis.host }
output "redis_port" { value = module.redis.port }
EOF
terraform init -input=false -backend-config=../../backend.s3.hcl
terraform apply -auto-approve -input=false
data.terraform_remote_state.network: Reading...
data.terraform_remote_state.network: Read complete after 0s
...
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
Outputs:
redis_host = "myapp-dev-redis"
redis_port = 6379
Application layer (dev/30-app): reads both the network and platform layers:
cd ~/myapp-infra/live/dev/30-app
cat > main.tf <<'EOF'
terraform {
  backend "s3" { key = "dev/30-app/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}

locals {
  env = "dev"
  state_backend = {
    bucket = "tfstate", region = "us-east-1", endpoints = { s3 = "http://localhost:9000" }
    use_path_style = true, skip_credentials_validation = true, skip_requesting_account_id = true
    skip_metadata_api_check = true, skip_region_validation = true
  }
}

data "terraform_remote_state" "network" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "${local.env}/10-network/terraform.tfstate" })
}
data "terraform_remote_state" "platform" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "${local.env}/20-platform/terraform.tfstate" })
}

module "app" {
  source       = "../../../modules/web-service"
  env          = local.env
  network_name = data.terraform_remote_state.network.outputs.network_name
  image        = "myapp:1.0"
  replicas     = 2
  http_port    = 8081
  redis = {
    host = data.terraform_remote_state.platform.outputs.redis_host
    port = data.terraform_remote_state.platform.outputs.redis_port
  }
}

output "url" { value = module.app.url }
EOF
terraform init -input=false -backend-config=../../backend.s3.hcl
terraform apply -auto-approve -input=false
for i in 1 2 3 4; do curl -s localhost:8081/; done
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
Outputs:
url = "http://localhost:8081"
myapp v1.0 env=dev color=none host=1c2b3a4d5e6f hits=1
myapp v1.0 env=dev color=none host=9f8e7d6c5b4a hits=2
myapp v1.0 env=dev color=none host=1c2b3a4d5e6f hits=3
myapp v1.0 env=dev color=none host=9f8e7d6c5b4a hits=4

Consecutively increasing hits show the two replicas share the platform layer's Redis; alternating host values show nginx round-robins between replicas via the Docker DNS alias.

Observe “stale value” reads: in the network layer outputs , add output "owner" { value = "network-team" } but do not apply; in the application layer, run terraform console → data.terraform_remote_state.network.outputs, and the owner value does not appear. Then apply once more in the network layer; the application layer can then read it. Conclusion: A change to an output is also an “interface publication” that must be deployed.
Audit the contents of the state (laying groundwork for Module 5):
terraform -chdir=../20-platform state pull | jq '.resources[] | {type, name, attrs: (.instances[0].attributes | keys | length)}'
terraform -chdir=../20-platform state pull | jq -r '.resources[] | select(.type=="docker_container") | .instances[0].attributes.env'

Anyone who can read the platform-layer state can see the container env 's complete contents. If a password is stored there, it is effectively shared with every downstream stack.

Verify the blast radius: in the application layer, run terraform plan -destroy, and confirm the plan includes only the 5 application resources, with network and Redis not included. Do not actually destroy them; the integrated lab continues to use them.

Case 1: one apply deleted the production DNS zone

Problem: All infrastructure was in one state. During a refactor, the resource address of the Route 53 hosted zone changed, and the author forgot to write a moved block, so the “destroy aws_route53_zone” buried in 400 lines of plan changes went unnoticed, breaking DNS resolution for the whole site for 40 minutes (NS record changes also required re-delegation). Fix: DNS zones, KMS keys, and databases moved to a separate “foundation” state, with resources marked lifecycle { prevent_destroy = true }; in CI, parse terraform show -json plan, and once a delete action appears for a resource type on the high-risk list, require additional approval. Limitation:prevent_destroy Only effective while the configuration still exists; deleting the whole resource block makes the protection disappear too, so plan review is still required.

Case 2: remote_state leaked the database password

Problem: The platform layer used a plain random_password to generate the RDS password and exported it as a sensitive output; more than a dozen application stacks read the platform state via remote_state, and a security audit found that all application deployment roles could read the master password. Fix: Switch RDS to manage_master_user_password = true (password managed in Secrets Manager) or a write-only parameter (Module 5); the platform layer writes only the endpoint and secret ARN to SSM parameters; the application stack uses aws_ssm_parameter data sources, and IAM grants only /myapp/prod/platform/*. Limitation: Old passwords still exist in historical state versions (S3 versioning), so the password must be rotated and old versions cleaned up per the retention policy.

Case 3: deployment order after splitting state

Problem: After splitting into three layers, one requirement called for both “adding a subnet (network layer) + a new service using that subnet (application layer)”; the two PRs were merged in reverse order, and the application-layer apply failed because the output did not exist. Fix: Adopt the convention “publish the interface before consuming it”: the network-layer PR is merged and applied first; the application layer's remote_state uses defaults or try() to stay compatible with older versions; in CI, run in directory-prefix order (10 → 20 → 30). Limitation: More complex dependency orchestration can be delegated to Terragrunt's dependency dependency block or HCP Terraform Stacks.

Common errors and fixes

Error: Unsupported attribute ... This object does not have an attribute named "network_name". (on data.terraform_remote_state.network.outputs)

Cause:① Wrong key or wrong environment, so an empty state was read; ② the lower layer has not yet applied the output; ③ the output is defined in a child module rather than the root module.

terraform -chdir=../10-network output
terraform console <<< 'data.terraform_remote_state.network.outputs'

Fix: Check the key; export from the lower layer's root module and apply; if needed, use defaults as a temporary bridge.

Error: Unable to find remote state ... No stored state was found for the given workspace in the given backend.

Cause: The specified key does not exist in the bucket (the lower layer was never deployed, or the workspace differs; remote_state reads the default workspace unless the workspace argument is set).

Fix: Deploy the lower layer first; or confirm the workspace argument matches the other side's.

Error: error loading state: operation error S3: GetObject, https response error StatusCode: 403, api error AccessDenied

Cause: The consumer role lacks the s3:GetObject permission on the other side's state object (or KMS decrypt kms:Decrypt permission).

Fix: Grant access to the specific key prefix as needed; or this is actually the correct denial, which means the necessary values should be shared via parameter store instead.

After the split, plan shows resources to destroy: # module.redis.docker_container.redis will be destroyed

Cause: The resource block was removed from the old stack's code without adding a removed { lifecycle { destroy = false } } block.

Fix: Stop the apply immediately; add a removed block in the old stack and re-plan, confirming it shows “will no longer be managed by Terraform” rather than destroy.

Error: Cycle: data.terraform_remote_state.app, module.network...

Cause: A cross-stack circular reference appeared (the network layer reads an output from the application layer, and the application layer reads from the network layer). Terraform can detect cycles within a single state; cycles across states are more hidden and show up as “no one can deploy first.”

Fix: Dependencies must flow downward only; extract values both sides need into a lower layer, or have them written to parameter store after deployment instead.

Command-line exercises
1. List all dev-environment state objects in the bucket and their version counts.
docker run --rm --network tf-lab -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION=us-east-1 \
  amazon/aws-cli --endpoint-url http://tf-minio:9000 s3api list-object-versions --bucket tfstate --prefix dev/ \
  --query 'Versions[].[Key,VersionId,LastModified]' --output table
2. Find all attribute paths marked as sensitive in the platform-layer state.
terraform -chdir=live/dev/20-platform state pull | jq '.resources[].instances[] | select(.sensitive_attributes|length>0) | .sensitive_attributes'
Scenario analysis
The security team requires that the application team cannot see any database credentials, but the application stack needs the database endpoint and security group ID. Currently the application stack reads the platform layer via remote_state. How would you refactor it?

① The platform layer writes the endpoint, port, security group ID, and Secret ARN to SSM parameters (or App Configuration), with the path /myapp/prod/platform/*; ② the application stack switches to aws_ssm_parameter data sources and removes remote_state; ③ IAM: the application deployment role removes the platform state's s3:GetObject access, and is granted read-only permission on only that parameter path ssm:GetParameter; ④ the platform layer switches to write-only / managed passwords so the state itself contains no passwords; ⑤ rotate the existing password and clean up old state versions. At runtime, the application reads Secrets Manager with its own identity rather than having the secret injected at deployment time.

Verified teaching videos

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · Remote backends and project organization chapter; for the cross-state reference permission discussion, this lesson takes precedence

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3; storyboards and narration scripts are provided.

Shot 1 · 0–20s
Visual: a bomb explodes at the center of a large state, and ripples spread to cover all resources; it switches to three small squares, with ripples covering only one of them.
Narration: the blast radius is the worst-case scope a single apply can affect.
Shot 2 · 20–50s
Visual: the application layer sends a request, an arrow passes through S3 to retrieve the network layer's state file, extracts only the outputs field, and fills it into application-layer parameters.
Narration: remote_state reads the outputs written by the other side's last apply.
Shot 3 · 50–70s
Visual: zoom into the state file; besides outputs, it contains password fields with lock icons that every reader can see.
Narration: but it requires reading the entire state, which may contain secrets.
Shot 4 · 70–90s
Visual: the producer puts three values into drawers in the parameter store; the consumer gets keys only to those three drawers.
Narration: when sharing across teams, explicitly publish the needed values and grant access by parameter.
or score ≥ 70% on the quiz

Module 4 · Multi-region and multi-account/subscription

24:00 – 32:00 · Accounts/subscriptions are the strongest isolation boundary, and regions are failure domains; Terraform uses provider configuration to express “where, and as whose identity”
8 minutesAWS provider 6.x resource-level regionTerraform provider does not support for_each★★★★☆
Learning objectives
  • Use provider alias + module providers = {} mappings to manage multiple regions/accounts; understand the configuration_aliases configuration and its limits.
  • Know that Terraform's provider block does not support for_each/count (OpenTofu supports it since 1.9), and since AWS provider 6.0 most resources support a top-level region argument, which can be used at the resource level with for_each to iterate over regions.
  • Understand the hierarchy of AWS Organizations (OUs, SCPs) and Azure management groups/subscriptions, and the baseline provided by a “landing zone”; know which layer Terraform is responsible for.
Prerequisites: Azure/AWS authentication from Lessons 3 and 4, and OIDC from Lesson 5. Importance:★★★★☆

What: regions, accounts/subscriptions, landing zones

  • Region: Physical failure domain and data residency boundary. The primary region for this lesson is Azure canadacentral / AWS ca-central-1, and the DR region is Azure canadaeast / AWS ca-west-1 or us-east-1 (global services such as CloudFront certificates must be in us-east-1).
  • Account (AWS) / subscription (Azure): A hard boundary for billing, quotas, IAM, and APIs. Separating production and non-production into different accounts/subscriptions is the industry baseline.
  • AWS Organizations: management account → OUs (such as Security, Infrastructure, Workloads/Prod, Workloads/NonProd, Sandbox) → member accounts; SCP set permission ceilings on OUs (for example, prohibit leaving specified regions, prohibit disabling CloudTrail).
  • Azure management groups: tenant root management group → Platform (Identity, Management, Connectivity) / Landing zones (Corp, Online) / Sandbox → subscriptions; Azure Policy and RBAC are inherited at management groups.
  • Landing zone: A pre-built multi-account/multi-subscription baseline (identity, log archive, security audit, network hub, guardrail policies) so application teams can “move in ready.” On AWS it is implemented by Control Tower (and Account Factory for Terraform, AFT); on Azure, Azure Landing Zones (with an official Terraform implementation; the ALZ modules in Azure Verified Modules are currently recommended; for exact module names and versions, refer to learn.microsoft.com).

Why: why use account/subscription isolation rather than just tags or resource groups

  • The impact of IAM misconfiguration is contained within one account; a prod credential leak does not affect other accounts, and vice versa.
  • Quotas (vCPUs, EIPs, public IPs) do not compete with each other; costs are naturally allocated.
  • SCPs / Azure Policy can set a ceiling above accounts/subscriptions that “no one can break through,” including account administrators.

How: how Terraform expresses “where, and as whose identity”

RequirementTerraform / provider mechanismNotes
Manage two regions in one configurationprovider "aws" { alias = "dr" region = "ca-west-1" }, set the provider in the resource provider = aws.drClassic approach; applies to all providers
AWS: resource-level regionAWS provider 6.0+: most resources, data sources, and ephemeral resources have a top-level region region argumentOne provider configuration is enough to work across regions; can be combined with resource for_each
Create providers by iterating over regionsTerraform does not support provider for_each; OpenTofu 1.9+ supports it (must be used with alias together).In Terraform, you need to write one provider block + one module call per region (can use code generation or Terragrunt)
AWS cross-accountassume_role { role_arn = "arn:aws:iam::<prod>:role/tf-deploy" }CI first uses OIDC to enter the “deployment account,” then AssumeRole into the target account
Azure cross-subscriptionprovider "azurerm" { alias = "hub" subscription_id = "…" }starting with azurerm 4.0 subscription_id must be explicitly provided (or ARM_SUBSCRIPTION_ID)
Azure resource provider registrationazurerm 5.0 from resource_provider_registrations defaults to none,skip_provider_registration removed;use resource_providers_to_register = ["Microsoft.App", …] explicitly register the required RPs
a module requires multiple providerschild module configuration_aliases = [aws.primary, aws.dr], the caller providers = { aws.primary = aws.cac1, aws.dr = aws.caw1 }see Module 2

When: how to split state by account/region

  • One state corresponds to only one account/subscription (cross-account “connection” resources such as VPC peering / TGW attachment and vWAN connections are exceptions, as they naturally require providers at both ends).
  • Split state by region for region-level resources: live/prod/ca-central-1/10-network,live/prod/ca-west-1/10-network—when one region fails, plan/apply in the other region is unaffected (the state itself must also be stored in a location that does not depend on the failed region, for example by enabling S3 cross-region replication).
  • Global resources (IAM, Route 53 zones, Entra apps, Front Door) go in live/global/.
  • Creating accounts/subscriptions (AFT,aws_organizations_account, subscription aliases azurerm_subscription) belongs to the platform team's “account factory” and is not kept with workload code.

Comparison with similar technologies

TerraformOpenTofu 1.9+TerragruntHCP Terraform Stacks
Expand by region listWrite multiple providers/modules by hand; AWS can use resource-level regionprovider for_each + provider = aws.by_region[each.key]One directory per region,region.hcl injectdeployment block / provider configuration can be expanded per deployment (refer to the official documentation)
Common misconceptions① “With resource region in AWS 6.x, you no longer need multiple states”—it solves a “syntax” problem, not a “blast radius” problem; DR-region resources are still recommended in a separate state. ② “Providers can be enabled with a count toggle”—Terraform does not support this; when conditional behavior is needed, place the provider in the root module and control whether the module that uses it is called. ③ “For multiple subscriptions, just switch az account set”—azurerm 4.0+ requires explicit subscription_id, and relying on the CLI's current subscription makes CI and local behavior inconsistent. ④ “A landing zone is a Terraform module”—it is a combination of organization, process, and baseline; Terraform is just one implementation method.

Architecture diagram: state and identity for multi-account + multi-region

AWS Organizations Management (organization/billing only) OU Security: log-archive, audit OU Infrastructure: network, cicd OU Workloads/Prod: myapp-prod OU Workloads/NonProd: dev, stage SCP: only ca-central-1 / ca-west-1 allowed/ us-east-1 (global services) GitHub ActionsOIDC token (aud sts.amazonaws.com) cicd accountrole/gha-terraform AssumeRole myapp-prod account · role/tf-deploy ca-central-110-network20-platform30-app(primary region) ca-west-110-network20-platform (replica)30-app (warm standby)(DR region) globalRoute 53 zone / IAM / ACM (us-east-1) state bucket (in cicd or a dedicated account)Versioning + cross-region replication + KMS
Figure 4-1: one state = one account × one region × one layer; state storage is placed in a separate account and replicated across regions

Azure equivalent: management group → subscription → state

Tenant root management group Platform Landing Zones Sandbox sub-connectivity (hub VNet) sub-myapp-prod (Corp) sub-myapp-nonprod Azure Policy (inherited)Allowed regions canadacentral/canadaeastEnforce diagnostic logs, prohibit public IPs (Corp)
Figure 4-2: “connection” resources such as VNet peering require provider configurations (aliases) for both the hub and spoke subscriptions

Animation: identity chain and API calls for a cross-account / cross-subscription apply

Select a cloud platform, then play. The animation shows how the provider plugin in the ConfigureProvider stage obtains credentials (OIDC → STS / Entra ID), and then which regional endpoint each resource's API request is sent to and under which identity it runs.

Ready.
$ terraform apply

Core syntax

Syntax / commandPurposeNotes
provider "aws" { alias = "dr" region = "ca-west-1" }Define a second configurationReference: provider = aws.dr
module "x" { providers = { aws = aws.dr } }Pass a non-default configuration into a child moduleIn the child module, the aws is dr
resource "aws_vpc" "x" { region = "ca-west-1" }AWS 6.x resource-level regiondoes not need an extra provider block
assume_role { role_arn = … session_name = … }Cross-accountChained AssumeRole is possible (the provider supports multiple assume_role blocks; refer to the provider documentation)
terraform providersShow each module's required providers and where their configuration comes fromTroubleshoot alias mapping
aws sts get-caller-identity / az account showConfirm the current identityWrite to the CI log for auditing

AWS: two regions + cross-account (classic alias approach)

provider "aws" {
  region = "ca-central-1"
  assume_role {
    role_arn     = "arn:aws:iam::222222222222:role/tf-deploy"
    session_name = "tf-myapp-prod"
  }
  default_tags { tags = { app = "myapp", env = "prod", managed-by = "terraform" } }
}

provider "aws" {
  alias  = "dr"
  region = "ca-west-1"
  assume_role {
    role_arn     = "arn:aws:iam::222222222222:role/tf-deploy"
    session_name = "tf-myapp-prod-dr"
  }
}

module "network_primary" {
  source = "../../modules/aws-network"
  cidr   = "10.20.0.0/16"
}

module "network_dr" {
  source    = "../../modules/aws-network"
  cidr      = "10.21.0.0/16"
  providers = { aws = aws.dr }
}

check "right_account" {
  data "aws_caller_identity" "me" {}
  assert {
    condition     = data.aws_caller_identity.me.account_id == "222222222222"
    error_message = "Current credentials are not for the myapp-prod account!"
  }
}

AWS 6.x: resource-level region + for_each over regions

variable "log_regions" {
  type    = set(string)
  default = ["ca-central-1", "ca-west-1"]
}

resource "aws_s3_bucket" "logs" {
  for_each = var.log_regions
  region   = each.key                     # AWS provider 6.0+
  bucket   = "myapp-prod-logs-${each.key}"
}

resource "aws_cloudwatch_log_group" "app" {
  for_each          = var.log_regions
  region            = each.key
  name              = "/myapp/prod/app"
  retention_in_days = 30
}

The official enhanced region support guide notes: the pre-6.0 approach of “one provider block per region” is still valid and not deprecated; a few global resources (such as IAM) do not support region argument. When migrating from the alias approach to resource-level region, if resource addresses are unchanged, the plan will only show the region attribute being “written”; confirm in the plan that nothing is replaced.

OpenTofu's provider for_each (for comparison; not available in Terraform)

# OpenTofu 1.9+ only; Terraform reports Unsupported argument
provider "aws" {
  alias    = "by_region"
  for_each = toset(["ca-central-1", "ca-west-1"])
  region   = each.key
}
module "network" {
  source    = "./modules/aws-network"
  for_each  = toset(["ca-central-1", "ca-west-1"])
  providers = { aws = aws.by_region[each.key] }
}

Azure: hub and spoke subscriptions (azurerm 5.x)

terraform {
  required_providers {
    azurerm = { source = "hashicorp/azurerm", version = "~> 5.14" }
  }
}

provider "azurerm" {
  subscription_id                = var.spoke_subscription_id
  resource_providers_to_register = ["Microsoft.App", "Microsoft.Network", "Microsoft.OperationalInsights"]
  features {}
}

provider "azurerm" {
  alias           = "hub"
  subscription_id = var.hub_subscription_id
  features {}
}

data "azurerm_virtual_network" "hub" {
  provider            = azurerm.hub
  name                = "vnet-hub-canadacentral"
  resource_group_name = "rg-connectivity"
}

resource "azurerm_virtual_network_peering" "spoke_to_hub" {
  name                      = "peer-myapp-prod-to-hub"
  resource_group_name       = azurerm_resource_group.app.name
  virtual_network_name      = azurerm_virtual_network.app.name
  remote_virtual_network_id = data.azurerm_virtual_network.hub.id
}

resource "azurerm_virtual_network_peering" "hub_to_spoke" {
  provider                  = azurerm.hub
  name                      = "peer-hub-to-myapp-prod"
  resource_group_name       = "rg-connectivity"
  virtual_network_name      = data.azurerm_virtual_network.hub.name
  remote_virtual_network_id = azurerm_virtual_network.app.id
}

Common error: After upgrading to azurerm 5.x, the first apply reports that a resource provider is not registered (for example, MissingSubscriptionRegistration)—starting with 5.0, automatic registration is no longer the default; you need to set resource_providers_to_register or have the platform team pre-register them. Production use: Write permission on the hub subscription is usually granted only to the network team; cross-subscription peering can be split so that the spoke side is created by the application stack and the hub side by the network stack, avoiding the application stack holding hub write permission.

Lab 4: simulate a “second region” with a second Docker daemon, and experience provider aliases and module providers mapping (about 7 minutes)

There is only one Docker host locally, so we use docker-in-docker (docker:29-dind) to start a second, independent Docker daemon representing the DR region; the resources of the two daemons are completely isolated, just like API endpoints of two regions.

Start “region B” (lab only: privileged container, port 2375 without TLS, bound only to 127.0.0.1):
docker run -d --name region-b --privileged \
  -e DOCKER_TLS_CERTDIR="" -p 127.0.0.1:2375:2375 docker:29-dind
sleep 8
docker -H tcp://127.0.0.1:2375 version --format '{{.Server.Version}}'
29.x.x
Security note A Docker API without TLS is equivalent to root access; always bind only to 127.0.0.1, and remove it after the lab.
Write a module that requires two provider configurations:
mkdir -p ~/myapp-infra/modules/edge-pair ~/myapp-infra/live/dev/40-multiregion
cat > ~/myapp-infra/modules/edge-pair/main.tf <<'EOF'
terraform {
  required_providers {
    docker = {
      source                = "kreuzwerker/docker"
      version               = "~> 4.7"
      configuration_aliases = [docker.primary, docker.dr]
    }
  }
}
variable "name" { type = string }

resource "docker_image" "nginx_primary" {
  provider     = docker.primary
  name         = "nginx:1.29-alpine"
  keep_locally = true
}
resource "docker_image" "nginx_dr" {
  provider = docker.dr
  name     = "nginx:1.29-alpine"
}
resource "docker_container" "primary" {
  provider = docker.primary
  name     = "${var.name}-primary"
  image    = docker_image.nginx_primary.image_id
  ports {
    internal = 80
    external = 8091
  }
}
resource "docker_container" "dr" {
  provider = docker.dr
  name     = "${var.name}-dr"
  image    = docker_image.nginx_dr.image_id
  ports {
    internal = 80
    external = 8092
  }
}
output "endpoints" {
  value = { primary = "localhost:8091 (host daemon)", dr = "region-b container :8092" }
}
EOF
Root module: define two provider configurations and map them to the module:
cat > ~/myapp-infra/live/dev/40-multiregion/main.tf <<'EOF'
terraform {
  backend "s3" { key = "dev/40-multiregion/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}

provider "docker" {
  alias = "region_a"                       # primary region: local daemon
  host  = "unix:///var/run/docker.sock"
}
provider "docker" {
  alias = "region_b"                       # DR region: dind daemon
  host  = "tcp://127.0.0.1:2375"
}

module "edge" {
  source = "../../../modules/edge-pair"
  name   = "myapp-dev-edge"
  providers = {
    docker.primary = docker.region_a
    docker.dr      = docker.region_b
  }
}
output "endpoints" { value = module.edge.endpoints }
EOF
cd ~/myapp-infra/live/dev/40-multiregion
terraform init -input=false -backend-config=../../backend.s3.hcl
terraform providers
terraform apply -auto-approve
Providers required by configuration:
.
├── provider[registry.terraform.io/kreuzwerker/docker] ~> 4.7
└── module.edge
    └── provider[registry.terraform.io/kreuzwerker/docker] ~> 4.7

Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Verify that resources land in the two “regions”:
docker ps --filter name=myapp-dev-edge --format '{{.Names}}'
docker -H tcp://127.0.0.1:2375 ps --format '{{.Names}}'
curl -sI localhost:8091 | head -1
myapp-dev-edge-primary
myapp-dev-edge-dr
HTTP/1.1 200 OK
Try provider for_each (expected to fail): in main.tf, rewrite the two providers as provider "docker" { alias = "r" for_each = toset(["a","b"]) … }, then run terraform validate, and observe the Terraform error (the error message is similar to Unsupported argument / An argument named "for_each" is not expected here). Revert it to the original. This confirms the conclusion of this module: in Terraform, providers can be expanded by region only when they are written explicitly.
Simulate a region failure: docker stop region-b then run terraform plan—the whole plan will fail because the DR provider cannot connect, and changes in the primary region are also blocked. This is exactly why DR-region resources should live in a separate state. Recovery: docker start region-b.
Cleanup:
terraform destroy -auto-approve
docker rm -f region-b

Case 1: unable to apply DR changes during a region failure

Problem: The network and database replicas for the primary and DR regions were in the same state, and the state bucket existed only in the primary region. When S3 in the primary region had a widespread outage, the team could not read the state or apply anything to the DR region. Fix: Split state by region; enable cross-region replication of the state bucket to the DR region, and prepare a backend configuration file pointing to the replica bucket (backend.dr.hcl); perform a real switchover once in a DR drill. Limitation: Replication is asynchronous; after switching, confirm the replica state is the latest version to avoid applying with stale state and causing a rollback.

Case 2: using SCP as a backstop for the “region allowlist”

Problem: A developer mistakenly set the provider region to us-west-2, creating a storage bucket containing personal data in a non-compliant region. Fix: Set an SCP on the Workloads OU that denies aws:RequestedRegion requests outside the allowlist (except global services); at the Terraform level, add validation in the module to accept only allowlisted regions; add policy checks in CI (Lesson 5). Limitation: SCPs do not apply to the management account; the exemption list for global services must be maintained.

Case 3: Azure subscription vending

Problem: Every new product required manually requesting a subscription, joining a management group, establishing peering with the hub, and configuring budgets and RBAC, taking two weeks. Fix: The platform team uses Terraform (subscription alias resources + management group association + budgets + network connectivity) to implement a subscription vending pipeline; the application team submits a single YAML/tfvars PR to get a subscription that complies with the landing zone baseline; the application team's Terraform manages only the resources within the subscription. Limitation: Creating subscriptions requires the appropriate roles on the EA/MCA billing account and usually can only be performed by the platform pipeline's identity; for specific resource and permission requirements, refer to the subscription vending documentation on learn.microsoft.com.

Common errors and fixes

Error: Provider configuration not present ... module.network_dr.aws_vpc.this ... provider["registry.terraform.io/hashicorp/aws"].dr is required

Cause: Removed the provider "aws" { alias = "dr" }, but the state still contains resources created with it.

Fix: First restore the provider block,destroy -target or migrate those resources before deleting. The lifecycle of a provider configuration must outlast the resources it manages.

Error: Missing required argument ... The argument "subscription_id" is required, but no definition was found.

Cause: Starting with azurerm 4.0, the subscription ID must be explicitly provided.

Fix: Set it in the provider subscription_id or export ARM_SUBSCRIPTION_ID; in multi-subscription scenarios, set it explicitly for each alias.

MissingSubscriptionRegistration: The subscription is not registered to use namespace 'Microsoft.App'

Cause: Starting with azurerm 5.0, resource providers are no longer automatically registered by default.

az provider register --namespace Microsoft.App --wait
az provider show -n Microsoft.App --query registrationState

Fix: Add to the provider resource_providers_to_register = ["Microsoft.App"], or have the platform team register them centrally; to restore the old behavior, set resource_provider_registrations = "legacy" (refer to the 5.0 upgrade guide).

Error: Module module.edge does not declare a provider named docker.primary ... (or) No configuration_aliases for docker.dr

Cause: The caller in providers = {} passed an alias that the child module does not declare.

Fix: In the child module's required_providers block, add configuration_aliases = [docker.primary, docker.dr].

operation error STS: AssumeRole, https response error StatusCode: 403, AccessDenied: User arn:aws:sts::111111111111:assumed-role/gha-terraform/... is not authorized to perform: sts:AssumeRole

Cause: The target account role's trust policy does not trust the cicd account's role, or the source role lacks sts:AssumeRole permission, or an SCP denies it.

aws sts get-caller-identity
aws iam get-role --role-name tf-deploy --query 'Role.AssumeRolePolicyDocument'   # run in the target account

Fix: Correct the Principal in the trust policy; check SCPs; check CloudTrail for the reason for the denial.

Command-line exercises
1. Check which providers each module in the current configuration requires, and the provider configurations actually used in the state.
terraform providers
terraform state pull | jq -r '.resources[] | "\(.module // "root") \(.type).\(.name) → \(.provider)"'
2. Use the AWS CLI to verify the identity chain for the prod deployment role (first the OIDC role, then the target account).
aws sts get-caller-identity
aws sts assume-role --role-arn arn:aws:iam::222222222222:role/tf-deploy --role-session-name check \
  --query 'AssumedRoleUser.Arn' --output text
Scenario analysis
myapp needs to expand to 3 regions (ca-central-1, ca-west-1, us-east-1); networking and applications are the same in each region. The team wants “adding a region changes only one line.” How would you design this in Terraform (not OpenTofu)?

Options: ① one directory per region live/prod/<region>/{10-network,30-app}, with the region as input; adding a region = copying a directory with just a few lines (or using Terragrunt region.hcl). This keeps the regional blast radius and is recommended. ② For AWS, one state can use 6.x resource-level region region + for_each, but all regions share one state, so an API outage in one region blocks all plans; not recommended for the main workload. ③ provider for_each is not available in Terraform; consider it if the team has adopted OpenTofu. Global resources (Route 53 latency/failover records, IAM) go in a separate global state, and each region's LB address is read via parameter store or remote_state.

Verified teaching videos

▶
Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners — freeCodeCamp.org
English · Azure provider configuration and authentication basics (recorded earlier; for changes to subscription_id and RP registration in azurerm 4.x/5.x, this lesson takes precedence)
▶
Terraform Course - Automate your AWS cloud infrastructure — freeCodeCamp.org
English · AWS provider basics; multi-account/resource-level region not covered

No verified video specifically covering “Terraform multi-account assume_role + multi-region alias” was found.

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3; storyboards and narration scripts are provided.

Shot 1 · 0–25s
Visual: the organization tree expands: management account, security OU, workloads OU; SCPs sit like a ceiling over the OUs.
Narration: accounts are the strongest isolation boundary; SCPs set a ceiling no one can break through.
Shot 2 · 25–55s
Visual: CI takes an OIDC token, exchanges it for temporary credentials, then assumes the target account's role; the keys are passed along in sequence.
Narration: the provider completes the identity chain during configuration (OIDC, AssumeRole), and only then starts calling cloud APIs.
Shot 3 · 55–80s
Visual: two provider cards, primary and dr, with arrows pointing to the two regional endpoints; a module's providers mapping table connects them.
Narration: aliases define multiple configurations; the providers argument hands them to the module.
Shot 4 · 80–100s
Visual: the provider block reads for_each and is marked with a red cross; beside it, the region argument on an AWS resource is marked with a green check.
Narration: Terraform providers cannot use for_each; since AWS 6.0 you can set region directly on resources.
or score ≥ 70% on the quiz

Module 5 · Secrets: ephemeral resources and write-only arguments

32:00 – 40:00 · sensitive only “masks” values; ephemeral and write-only are what keep them off disk
8 minutesephemeral 1.10 · write-only 1.11Requires provider support★★★★★
Learning objectives
  • Distinguish four kinds of values: regular values,sensitive (displayed masked but stored in state/plan),ephemeral (1.10: not stored in state/plan),write-only arguments (1.11: resource arguments are passed only to the provider and not stored in state/plan).
  • Know how to write ephemeral blocks,ephemeral = true variables and child-module outputs; know in which contexts ephemeral values can be used; know how to use *_wo + *_wo_version set and rotate passwords.
  • Plan how to handle “secrets already in state”: rotate them, clean up state history versions, apply encryption and access control, and switch to managed passwords.
Prerequisites: State structure and the provider plugin model. Importance:★★★★★ (a state leak = all secrets leaked)

What: comparison of the four kinds of values

TypeSyntaxCLI outputplan filestateAvailable since
Regular valuevariable "x" {}PlaintextPlaintextPlaintext—
sensitivesensitive = true(sensitive value)PlaintextPlaintext (marked in sensitive_attributes)0.14+
ephemeral valueephemeral "type" "n" {},variable { ephemeral = true }, child module output { ephemeral = true }(ephemeral value)Not savedNot saved1.10+
write-only argumentResource argument such as password_wo (defined by the provider)Not shownNot savedNot saved (value is null)1.11+, and the provider resource supports it

Why: state is the largest secrets repository

Before 1.10, any password passed through Terraform—random_password.result, database password parameters, and values read from Secrets Manager data sources—are all written in plaintext to the state and plan files. The state can in turn be exposed to: all readers of the remote backend,terraform_remote_state consumers (Module 3), CI artifact storage (saved .tfplan files), and S3 version history. sensitive It only solves “don't print it in logs.”

How: the real mechanism

  • ephemeral resources: the provider implements OpenEphemeralResource / RenewEphemeralResource / CloseEphemeralResource RPC. Terraform, in each plan and apply run, opens the value when needed (for example, requesting a lease from Vault, reading from Secrets Manager, generating a random password), renews it if necessary, and closes it after downstream use is complete (for example, revoking the lease). The result exists only in memory.
  • ephemeral values can only flow to allowed contexts: write-only arguments, other ephemeral blocks,locals,ephemeral = true variables (with ephemeral enabled), in child modules ephemeral = true outputs,provider configuration, provisioners and connection. Flowing into a regular resource argument or a root module output produces an error at plan time.
  • write-only argument: an attribute marked WriteOnly in the resource schema. Terraform places the value into ApplyResourceChange the configuration and passes it to the provider; after the provider calls the cloud API, the new state returned must have this attribute as null. Because Terraform does not remember the old value, it cannot detect changes, so providers usually pair it with an ordinary argument *_wo_version, which you increment to trigger an update.
  • Common combinations: ephemeral "random_password" Generate → aws_secretsmanager_secret_version.secret_string_wo Store in secrets manager → aws_db_instance.password_wo Set the database password → the application reads it from the secrets store at runtime. The password never enters state.

Verified resources that support write-only (examples, not a complete list)

ProviderResourcewrite-only argumentVersion trigger argument
hashicorp/aws 6.xaws_db_instancepassword_wopassword_wo_version
hashicorp/aws 6.xaws_secretsmanager_secret_versionsecret_string_wosecret_string_wo_version
hashicorp/azurerm 5.xazurerm_key_vault_secretvalue_wovalue_wo_version
hashicorp/azurerm 5.xazurerm_postgresql_flexible_serveradministrator_password_woadministrator_password_wo_version
hashicorp/azurermazurerm_mysql_flexible_serveradministrator_password_woSame pattern as above

Verified ephemeral resource examples: random_password (hashicorp/random),local_command (hashicorp/local),aws_secretsmanager_secret_version,aws_secretsmanager_random_password,aws_ssm_parameter,aws_eks_cluster_auth (aws 6.x),azurerm_key_vault_secret,azurerm_key_vault_certificate (azurerm 5.x). kreuzwerker/docker 4.7.0 does not have write-only arguments, so the local lab uses a provisioner to demonstrate the equivalent mechanism.

When: selection guide

  • Cloud service can manage the password itself → prefer managed (RDS manage_master_user_password, Azure database Entra ID authentication, managed identity), so Terraform never touches the password.
  • The password must be set by Terraform → ephemeral generation/reading + write-only argument + version-number rotation.
  • The provider configuration needs a secret (for example, the postgresql provider's password or a Vault token) → read it with an ephemeral resource and pass it to the provider configuration.
  • The resource does not support write-only → fall back: store the secret in a secrets vault, and have the resource reference only the secret's ID/ARN (read by the application at runtime).

What to do with secrets already in state

  1. Assume it has leaked; rotate: after switching to write-only/managed, immediately rotate the actual password (increment *_wo_version).
  2. Clean up history: S3/Blob versioning retains old state versions. Delete versions containing old passwords according to the retention policy (first confirm a new usable backup exists). Old state versions are equally visible in HCP Terraform.
  3. Tighten access: the state bucket uses KMS (SSE-KMS / Azure customer-managed keys), and read permission is granted only to pipeline roles; do not treat the plan .tfplan file as a publicly downloadable CI artifact.
  4. OpenTofu users can enable client-side state/plan encryption (available since OpenTofu 1.7); the Terraform CLI itself has no equivalent client-side encryption and relies on the backend's server-side encryption.
Common misconceptions① “sensitive = true keep the value out of state”—wrong; it only affects display. ② “A password generated by an ephemeral random_password can be used directly by the database”—it regenerates on every run; with write-only, the value is only actually written when the version number changes; otherwise the database keeps the first password while the value you hold has changed, so you must also write it to the secrets store (same run, same value). ③ “The plan shows changes after modifying a write-only argument”—it does not; Terraform does not know the old value and can only see the version number. ④ “Ephemeral outputs can be used in the root module”—ephemeral = true output can only be used in child modules.

Data flow diagram: the lifecycle of a password (AWS example)

ephemeralrandom_password.dbOpen → memory only aws_secretsmanager_secret_versionsecret_string_wo = ephemeral…resultsecret_string_wo_version = 1In state: wo = null, version = 1 aws_db_instancepassword_wo = ephemeral…resultpassword_wo_version = 1In state: password_wo = null PutSecretValue CreateDBInstance Secrets ManagerThe only place storing the password RDS PostgreSQLmaster password set read by the application at runtime terraform.tfstateNo passwordOnly *_wo_version
Figure 5-1: in the same run, the ephemeral value is written to both the secrets store and the database; only the version number is left in state

Sequence diagram: RPCs for an ephemeral resource in one apply

Terraform coreprovider plugin (gRPC)External system (Vault / API) OpenEphemeralResource Request lease / read secret result (memory only) + RenewAt RenewEphemeralResource (if it takes longer than the lease period) After downstream ApplyResourceChange completes: CloseEphemeralResource Revoke lease plan and apply each independently run Open/Close once—the value may differ between the two phases
Figure 5-2: ephemeral resources have no “state,” only a “session”

Interactive demo: tracing value flow—who wrote the password where?

Select how the password is handled and click play. The animation follows the path from tfvars/generation → plan (memory + .tfplan file) → ApplyResourceChange cloud API → state → terraform_remote_state to the consumer, marking at each “on-disk point” whether plaintext appears.

Ready.
$ terraform plan -out=tf.plan

Core syntax

SyntaxPurposeNotes
ephemeral "random_password" "db" { length = 24 }Generate a password that exists only in memoryReference: ephemeral.random_password.db.result; regenerated on every run
variable "token" { ephemeral = true }Input value is not written to plan/stateWhen applying a saved plan, the variable must be provided again
output "x" { ephemeral = true }Child module passes an ephemeral value to the parent moduleNot available in the root module
ephemeralasnull(value)Convert ephemeral values to null (preserving structure)New in 1.10; passes objects containing ephemeral values to regular contexts
password_wo / password_wo_versionwrite-only argument + version triggerWritten again only when the version is incremented
terraform state pull | grep -c 'secret'Audit plaintext in stateCan be used as a “secret scan” in CI

AWS: RDS with the password kept out of state (extension of the official documentation example)

ephemeral "random_password" "db" {
  length           = 24
  override_special = "!#$%^&*()-_=+[]{}<>:?"
}

resource "aws_secretsmanager_secret" "db" {
  name = "myapp/prod/db-master"
}

resource "aws_secretsmanager_secret_version" "db" {
  secret_id                = aws_secretsmanager_secret.db.id
  secret_string_wo         = ephemeral.random_password.db.result
  secret_string_wo_version = var.db_password_version     # +1 when rotating
}

resource "aws_db_instance" "main" {
  identifier          = "myapp-prod"
  engine              = "postgres"
  instance_class      = "db.t4g.micro"
  allocated_storage   = 20
  username            = "myapp_admin"
  password_wo         = ephemeral.random_password.db.result
  password_wo_version = var.db_password_version
  skip_final_snapshot = false
  lifecycle { prevent_destroy = true }
}

variable "db_password_version" {
  type    = number
  default = 1
}

Key points: Two resources in the same run reference the same ephemeral value and share the same version number: when the version is incremented, the secrets store and database are updated together to stay consistent. Incrementing only one of them causes the password in the secrets store to differ from the database. The reverse is also possible: first use aws_secretsmanager_random_password (ephemeral) to generate, or after rotation in the secrets store, via ephemeral "aws_secretsmanager_secret_version" read and then pass to password_wo.

Azure: Key Vault + PostgreSQL Flexible Server (azurerm 5.x)

ephemeral "random_password" "pg" {
  length = 24
}

resource "azurerm_key_vault_secret" "pg_admin" {
  name             = "pg-admin-password"
  key_vault_id     = azurerm_key_vault.main.id
  value_wo         = ephemeral.random_password.pg.result
  value_wo_version = var.pg_password_version
}

resource "azurerm_postgresql_flexible_server" "main" {
  name                              = "psql-myapp-prod-cc"
  resource_group_name               = azurerm_resource_group.main.name
  location                          = "canadacentral"
  version                           = "16"
  sku_name                          = "B_Standard_B1ms"
  storage_mb                        = 32768
  administrator_login               = "myappadmin"
  administrator_password_wo         = ephemeral.random_password.pg.result
  administrator_password_wo_version = var.pg_password_version
}

PostgreSQL versions and SKU availability depend on the region. A better approach is to enable Entra ID authentication so the application connects with a managed identity, eliminating the need for a password entirely.

Pass the ephemeral secret to the provider configuration

ephemeral "aws_secretsmanager_secret_version" "db" {
  secret_id = "myapp/prod/db-master"
}

provider "postgresql" {
  host     = aws_db_instance.main.address
  username = "myapp_admin"
  password = ephemeral.aws_secretsmanager_secret_version.db.secret_string
}

Lab 5: compare secret traces in state, and use a provisioner to demonstrate “version-triggered writes without touching disk” (about 8 minutes)

Prepare the lab directory:
mkdir -p ~/myapp-infra/live/dev/50-secrets-demo && cd ~/myapp-infra/live/dev/50-secrets-demo
cat > versions.tf <<'EOF'
terraform {
  required_version = ">= 1.11"
  backend "s3" { key = "dev/50-secrets-demo/terraform.tfstate" }
  required_providers {
    random = { source = "hashicorp/random", version = "~> 3.9" }
    local  = { source = "hashicorp/local",  version = "~> 2.9" }
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}
EOF
Counterexample: regular random_password:
cat > bad.tf <<'EOF'
resource "random_password" "bad" {
  length = 20
}
output "bad" {
  value     = random_password.bad.result
  sensitive = true
}
EOF
terraform init -input=false -backend-config=../../backend.s3.hcl
terraform apply -auto-approve
terraform output bad                      # masked
terraform output -raw bad; echo           # plaintext!
terraform state pull | jq -r '.resources[] | select(.type=="random_password") | .instances[0].attributes.result'
bad = <sensitive>
q7#Zp0V!m2Lx9$Tb4@Rn
q7#Zp0V!m2Lx9$Tb4@Rn

sensitive only blocks CLI display; state and output -raw are both plaintext.

ephemeral version: try using it on a regular argument (expected error):
cat > eph.tf <<'EOF'
ephemeral "random_password" "good" {
  length = 20
}
resource "docker_container" "wrong" {
  name  = "secrets-demo-wrong"
  image = "redis:7-alpine"
  env   = ["PASSWORD=${ephemeral.random_password.good.result}"]
}
EOF
terraform plan 2>&1 | grep -A4 "Error"
│ Error: Invalid use of ephemeral value
│
│   with docker_container.wrong,
│   on eph.tf line 7, in resource "docker_container" "wrong":
│ Ephemeral values are not valid in resource arguments, because resource instances must persist between Terraform phases.
Equivalent mechanism demo: set the Redis password using a “local secrets store” + ephemeral + version trigger. The docker provider has no write-only argument, so we use local_command (ephemeral, simulating reading from the secrets store) + terraform_data provisioner (allows ephemeral values) + triggers_replace (equivalent to *_wo_version):
mkdir -p ~/.tf-lab-secrets && chmod 700 ~/.tf-lab-secrets
openssl rand -base64 18 > ~/.tf-lab-secrets/redis_password && chmod 600 ~/.tf-lab-secrets/redis_password
rm eph.tf
cat > good.tf <<'EOF'
variable "redis_password_version" {
  type    = number
  default = 1
}

# Simulates “reading from the secrets store”: re-executed on every plan/apply; the result is not stored in state
ephemeral "local_command" "redis_password" {
  command   = "cat"
  arguments = [pathexpand("~/.tf-lab-secrets/redis_password")]
}

resource "docker_container" "redis" {
  name  = "secrets-demo-redis"
  image = "redis:7-alpine"
}

# Equivalent to a write-only argument: the value is passed only at execution time; state only remembers the version number
resource "terraform_data" "set_redis_password" {
  triggers_replace = [docker_container.redis.id, var.redis_password_version]

  provisioner "local-exec" {
    command = "docker exec secrets-demo-redis redis-cli CONFIG SET requirepass \"$PW\""
    environment = {
      PW = trimspace(ephemeral.local_command.redis_password.stdout)
    }
  }
}
EOF
terraform apply -auto-approve
ephemeral.local_command.redis_password: Opening...
ephemeral.local_command.redis_password: Opening complete after 0s
docker_container.redis: Creating...
terraform_data.set_redis_password: Provisioning with 'local-exec'...
terraform_data.set_redis_password (local-exec): (output suppressed due to sensitive value in config)
ephemeral.local_command.redis_password: Closing...
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Verify: the password is in effect, but it is not in state:
docker exec secrets-demo-redis redis-cli ping
docker exec secrets-demo-redis redis-cli -a "$(cat ~/.tf-lab-secrets/redis_password)" --no-auth-warning ping
terraform state pull | grep -c "$(cat ~/.tf-lab-secrets/redis_password)"
terraform state pull | jq '.resources[] | select(.type=="terraform_data") | .instances[0].attributes.triggers_replace'
NOAUTH Authentication required.
PONG
0
{ "value": ["3fa1…", 1], "type": ["tuple", ["string","number"]] }
Rotate: generate a new password and increment the version number:
openssl rand -base64 18 > ~/.tf-lab-secrets/redis_password
terraform plan                                  # no changes: Terraform does not know the password changed
terraform apply -auto-approve -var redis_password_version=2   # version changed → write again
docker exec secrets-demo-redis redis-cli -a "$(cat ~/.tf-lab-secrets/redis_password)" --no-auth-warning ping

The first plan shows “No changes”. This is exactly the behavior of write-only arguments: changes in the value are invisible; only changes in the version number are visible. In production, keep the version number in tfvars and increment it with PR approval.

Cleanup: terraform destroy -auto-approve; then check whether the state's historical versions in the bucket still contain bad the password: aws s3api list-object-versions … --prefix dev/50-secrets-demo/ (commands as in Module 3). Delete all versions of this demo state, and understand that “secrets in historical versions” must be cleaned up separately.

Case 1: a plan file in CI artifacts leaked the database password

Problem: The pipeline published the terraform plan -out=tf.plan as an artifact for the apply job; the artifact was kept for 90 days, and every reader of the repository could download it. The plan file contained the RDS password in plaintext. Fix: Migrate to remote execution ephemeral + password_wo; encrypt the artifact storage, shorten the retention period, and let only the apply job's identity download it. Limitation: When using ephemeral variables, applying a saved plan requires these variables to be passed again (they are not saved in the plan); the pipeline must be adjusted accordingly.

Case 2: Vault dynamic credentials passed directly to a provider

Problem: Terraform used a long-lived database superuser password to manage PostgreSQL roles and grants. Fix: Use the Vault provider's ephemeral resource to request short-lived database credentials (the lease is revoked on Close) and pass them to the postgresql provider configuration; there are no credentials in state, and the lease expires when the run ends. Limitation: The Vault provider must provide the corresponding ephemeral resource (for version and resource names, refer to the registry documentation); plan and apply each request credentials once.

Case 3: cleanup plan for secrets in existing state

Problem: A security scan (terraform state pull | trufflehog -type tool) found 112 plaintext secrets across 37 states. Fix: Batch by resource type: ① rewrite and rotate those that support write-only (databases, Key Vault secrets); ② switch to managed passwords where supported; ③ change the remainder to reference only the secrets store ID; ④ finally clean up S3 history versions and enable SSE-KMS and access logging; ⑤ add a state secret-scanning gate to CI. Limitation: After switching to write-only, the first apply nulls out the old plaintext attributes in state, but old versions remain in history, so step ④ cannot be skipped.

Common errors and fixes

Error: Invalid use of ephemeral value ... Ephemeral values are not valid in resource arguments

Cause: An ephemeral value was assigned to a regular (non-write-only) resource argument, a root module output, or count/for_each.

Fix: Use the resource's *_wo argument (if available); or pass the secret ID from the secrets store instead; for outputs, declare them in the child module ephemeral = true.

Error: Unsupported argument ... An argument named "password_wo" is not expected here.

Cause: The provider version is too old, or the resource does not support write-only; it may also be that the Terraform CLI is below 1.11.

terraform version
terraform providers schema -json | jq '.provider_schemas[].resource_schemas.aws_db_instance.block.attributes.password_wo'

Fix: Upgrade the CLI and provider; confirm from the schema that the attribute exists and is marked write_only: true.

Changed the password but apply shows No changes, and the database still has the old password

Cause: write-only values are not tracked; only *_wo_version changes trigger an update.

Fix: Increment the version number; define “password rotation” as “a PR that increments the version number by +1.”

The application cannot connect to the database: the password in the secrets store does not match the database's actual password

Cause: Only the database's password_wo_version version was incremented, but not the secrets store version (or vice versa); the ephemeral random_password produced different values across two runs.

Fix: Both resources share the same version variable and the same ephemeral value; or only one side generates it (the secrets store), and the other side reads it via an ephemeral data source.

Error: No value for required variable ... (apply saved plan) variable "token" is ephemeral and must be set during apply

Cause: Ephemeral variables are not saved in the plan file; they must be provided again when applying a saved plan.

Fix:terraform apply -var "token=$TOKEN" tf.plan re-pass them with -var on the command line, or use TF_VAR_token environment variables (exact error wording depends on the actual version).

Command-line exercises
1. In the aws provider, list all aws_db_instance write-only attributes.
terraform providers schema -json | jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"].resource_schemas.aws_db_instance.block.attributes | to_entries[] | select(.value.write_only==true) | .key'
2. Add a gate in CI: fail if a known secret prefix (for example AKIA), and fail the job.
if terraform state pull | grep -Eq 'AKIA[0-9A-Z]{16}'; then echo "AWS access key found in state!"; exit 1; fi
Scenario analysis
The team changed random_password to ephemeral "random_password", passing it directly to aws_db_instance.password_wo, with the version number fixed at 1 but never written to any secrets store. What happens after going live? How do you fix it?

On the first apply, the database is set to the random password generated in this run, and then that value disappears; nothing saves it anywhere, so neither the application nor operations can log in. Later runs generate new random values, but since the version number is unchanged, they are not written to the database. Fix: in the same run, also write to Secrets Manager (secret_string_wo, same version number), or switch to RDS managed passwords; for a password that has already been “lost,” increment the version number to reset it and write it to the secrets store at the same time.

Verified teaching videos

No video published by HashiCorp that specifically covers ephemeral resources and write-only arguments and is verified via oEmbed was found. Recommended reading: the official blog and documentation:

▶
Introduction to HashiCorp Terraform with Armon Dadgar — HashiCorp, an IBM Company
English · Review of the core/provider/state architecture, explaining why “values entering state” is the default behavior (recorded before 1.10)

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3; storyboards and narration scripts are provided.

Shot 1 · 0–25s
Visual: a note with a password is covered with a “sensitive” mosaic and placed in a state safe; open the safe, and the words on the note are still clear.
Narration: sensitive only masks; the value is still written into state and plan.
Shot 2 · 25–55s
Visual: an ephemeral resource is like a one-time code pad: open, use, close, and it is destroyed; the timeline marks Open, Renew, Close.
Narration: ephemeral resources exist only in memory and are re-fetched on every run.
Shot 3 · 55–80s
Visual: the password flows along arrows to both the secrets store and the database; state shows only the number “version 1.”
Narration: a write-only argument hands the value to the provider; state records only the version number.
Shot 4 · 80–100s
Visual: the version number jumps from 1 to 2, and both targets update at once; in a “history versions” drawer, the old note is shredded.
Narration: rotation is just incrementing the version number; don't forget to clean up old secrets in historical state.
or score ≥ 70% on the quiz

Module 6 · Zero-downtime changes and blue-green

40:00 – 47:00 · Terraform defaults to “destroy then create”; zero downtime requires changing the order, avoiding name conflicts, waiting for health, and then shifting traffic
7 minutescreate_before_destroy · replace_triggered_by (1.2+)★★★★★
Learning objectives
  • Read the -/+ (destroy then create) and +/- (create then destroy), and explain create_before_destroy how it changes execution order in the dependency graph, and how it spreads to dependents.
  • Handle create_before_destroy introduced by name conflicts (name_prefix, hash/random suffix), and use health checks (wait, ALB health checks,min_healthy_percentage etc.) to ensure “delete the old only after the new is healthy.”
  • Implement with Terraform blue-green: two environments + one traffic switch (LB rules, DNS weighted records, Front Door weights), and understand why database changes should use expand/contract rather than a single apply.
Prerequisites: lifecycle blocks, dependency graph. Importance:★★★★★

What: Terraform replacement

When an argument is marked in the provider schema as ForceNew / RequiresReplace (for example, a docker container's image, many immutable attributes beyond AWS launch templates, Azure resource location), the provider in PlanResourceChange its response returns RequiresReplace, and Terraform splits this change into Delete + Create two graph nodes.

  • Default order (plan symbol -/+): destroy the old object first, then create the new one. There is a gap in between where “nothing exists.”
  • lifecycle { create_before_destroy = true } (plan symbol +/-): create the new object first, update all resources depending on it to point to the new object, and destroy the old object last. Before destruction, the old object is held in state as a deposed object; if it fails midway, it is cleaned up in the next apply.
  • Propagation: If A sets cbd, the resources A depends on must also be create-before-destroy during replacement, or a cycle forms; Terraform automatically applies cbd to these dependencies (see the official docs), so in the plan you may see resources without cbd also marked as “create then destroy +/-”.
  • replace_triggered_by: Forces replacement of this resource when a referenced resource or attribute changes (for example, replacing the container when the config file changes). terraform apply -replace=ADDR: one-time forced replacement.

Why: four prerequisites for zero downtime

  1. Order: new ones start first (cbd).
  2. No name conflicts: old and new objects must coexist, so unique names (container name, security group name, Key Vault name) must not be identical → use name_prefix name_prefix or a suffix.
  3. Readiness check:“Created successfully” must mean “ready to receive traffic”: provider wait parameters (docker wait = true, ASG wait_for_elb_capacity, ECS wait_for_steady_state) or deployment tool health checks.
  4. Traffic switching and draining: The LB first adds new targets, removes old targets, and waits for connections to drain (ALB deregistration delay); DNS must account for TTL caching.

How: three zero-downtime patterns

PatternWhat Terraform doesWho shifts trafficBest for
In-place rolling (platform-managed)updates only the task definition / revision / image tagPlatform: ECS rolling deployment, Container Apps revisions, K8s DeploymentMost stateless services (preferred)
cbd replacementNew object (unique name) → wait for healthy → update dependents → delete oldDependencies automatically point to the new object (LB targets, DNS aliases)Immutable infrastructure: ASG + launch template, VMs, and this lesson's containers
Blue-greenTwo complete environments coexist long-term or temporarily, with one variable controlling the “active color”LB listener rules, DNS weighted/alias records, Front Door / Traffic Manager weightsNeeds fast rollback, or needs validation before shifting traffic

Database changes: do not hand them to a single apply

  • Database instance: prevent_destroy = true; if replace appears in the plan, you must stop. Many parameters (major engine version, storage type, subnet group) cause replacement. AWS RDS offers managed Blue/Green Deployments (aws_db_instance of the blue_green_update block, for partial upgrade scenarios; see the provider docs for details); on Azure, the common approach is promoting a read replica or using a planned maintenance window.
  • Schema migrations: use application-side tools (Flyway, Alembic, Liquibase), following the expand → migrate → contract three-step process: first add new columns/tables (both old and new app versions must work) → release the new version and backfill data → after confirming the old version is retired, drop the old columns. Terraform manages the “database server”, not the “database content”.
  • Connection string/password rotation: first make old and new credentials valid at the same time (dual users, or AWSPENDING/AWSCURRENT from Secrets Manager rotation), then switch the application, and finally revoke the old credentials.

When

  • Resource is referenced by other resources and replacement would interrupt service → set cbd, and check name uniqueness.
  • Resource has a globally unique name that cannot take a suffix (some DNS names, storage account names) → cbd is not feasible; use blue-green instead (two names coexist) or a maintenance window.
  • Stateful resources (databases, disks with data) → do not use cbd to “upgrade”; use the managed upgrade/migration process.
Common misconceptions① “Adding cbd gives zero downtime” — a new object being “created successfully” does not mean it is “ready”, and a name conflict will make apply fail outright. ② “cbd can be removed at any time” — after removing cbd, resources that depend on it may still behave as implicit cbd (until the next replacement), and your plan behavior changes, which should be explained in review. ③ “Terraform handles canary rollout” — Terraform suits flipping a “switch”, not adjusting weights step by step every few minutes or automatic rollback; leave the latter to the deployment platform (CodeDeploy, Argo Rollouts, Front Door rules). ④ “DNS switches take effect immediately” — clients and resolvers cache according to the TTL (or even longer).

Sequence diagram: default replacement vs create_before_destroy

Default (-/+) Old container v1.0 serving Delete old Create new + health check New container v1.1 serving ⚠ No available instances: 502 / connection refused cbd (+/-) Old container v1.0 keeps serving (becomes a deposed object in state) Create new (unique name) + wait healthy Update dependents Drain → Delete old New container v1.1 serving (briefly coexisting with the old container) Time →
Figure 6-1 cbd turns the “gap period” into a “coexistence period” — during coexistence, names, IPs, and quotas must accommodate two copies

Architecture diagram: blue-green managed by Terraform

Users:8087 nginx LB (not replaced)conf generated by local_fileupstream = myapp-bg-${active}change → nginx -s reload active_color = blue After switch blue: myapp:1.0 × 2alias myapp-bg-blueRollback = set active_color back to blue green: myapp:1.1 × 2alias myapp-bg-greenDeploy first, verify first (direct connection to test port) Cloud equivalents: ALB listener rules / Route 53 weighted records / Front Door origin group weights
Figure 6-2 Blue-green = two sets of targets + one switch; the switch variable is the only value that needs to change in the “switch PR”

Core animation: replacement timing for create_before_destroy

Simulates one upgrade of the myapp image from 1.0 to 1.1 apply. The left side shows the graph nodes Terraform executes (real RPC: PlanResourceChange returns RequiresReplace → ApplyResourceChange (Delete/Create)), the right side shows container state, and the bottom shows request results per time slice from the load balancer's perspective. Toggle the switch to observe: default order, cbd + fixed name (conflict), cbd + unique name + health wait + drain.

Terraform graph node
Containers (Docker daemon)
LB request results every 0.5 seconds
Ready.
$ terraform apply -var image=myapp:1.1

Core syntax and commands

Syntax / commandPurposeNotes
lifecycle { create_before_destroy = true }Create before destroyplan shows +/-
lifecycle { replace_triggered_by = [terraform_data.cfg] }Replaces this resource when the referenced object changesCan only reference managed resources (or their attributes), often used together with terraform_data wrapper variables
lifecycle { prevent_destroy = true }Errors if the plan shows a destroyRequired for databases and DNS zones
terraform apply -replace='ADDR'Forces replacement of an objectReplaces the deprecated taint
terraform plan -json | jqMachine check for any delete.resource_changes[].change.actions in ["create","delete"] = cbd,["delete","create"] = default replacement
name_prefix = "myapp-"Generates a unique name via the providerMany AWS resources support it (SG, launch templates, target groups, IAM roles)
# Gate: require manual approval if the plan contains a delete-then-create replacement
terraform plan -out=tf.plan >/dev/null
terraform show -json tf.plan | jq -r '.resource_changes[] | select(.change.actions == ["delete","create"]) | .address'
module.app.docker_container.lb[0]

AWS: cbd pattern for ASG + launch template + ALB

resource "aws_launch_template" "app" {
  name_prefix   = "myapp-prod-"
  image_id      = var.ami_id
  instance_type = "t4g.small"
  lifecycle { create_before_destroy = true }
}

resource "aws_autoscaling_group" "app" {
  name_prefix          = "myapp-prod-${aws_launch_template.app.latest_version}-"
  min_size             = 2
  max_size             = 6
  vpc_zone_identifier  = var.private_subnet_ids
  target_group_arns    = [aws_lb_target_group.app.arn]
  health_check_type    = "ELB"
  wait_for_elb_capacity = 2          # creation is complete only after the new ASG has 2 healthy targets
  launch_template {
    id      = aws_launch_template.app.id
    version = aws_launch_template.app.latest_version
  }
  lifecycle { create_before_destroy = true }
}

resource "aws_lb_target_group" "app" {
  name_prefix          = "myapp-"
  port                 = 5000
  protocol             = "HTTP"
  vpc_id               = var.vpc_id
  deregistration_delay = 30           # drain
  health_check { path = "/healthz" }
  lifecycle { create_before_destroy = true }
}

Another, more modern approach is to update only the ASG's instance_refresh, letting the ASG roll-replace instances itself (min_healthy_percentage), and Terraform only changes the launch template version. ECS services and Azure Container Apps revisions are rolled out by the platform, and Terraform only changes the image.

DNS weighted blue-green (Route 53) and Front Door (Azure)

variable "active_color" { type = string }   # "blue" | "green"
locals { weights = { blue = var.active_color == "blue" ? 100 : 0, green = var.active_color == "green" ? 100 : 0 } }

resource "aws_route53_record" "app" {
  for_each       = local.weights
  zone_id        = var.zone_id
  name           = "app.example.com"
  type           = "CNAME"
  ttl            = 60
  set_identifier = each.key
  records        = [var.lb_dns[each.key]]
  weighted_routing_policy { weight = each.value }
}

# Azure Front Door: two origins in the same origin group, controlled with weight (0 means receives no traffic)
resource "azurerm_cdn_frontdoor_origin" "app" {
  for_each                       = { blue = var.blue_fqdn, green = var.green_fqdn }
  name                           = "myapp-${each.key}"
  cdn_frontdoor_origin_group_id  = azurerm_cdn_frontdoor_origin_group.app.id
  host_name                      = each.value
  origin_host_header             = each.value
  certificate_name_check_enabled = true
  enabled                        = true
  weight                         = local.weights[each.key] == 0 ? 1 : 1000
  priority                       = local.weights[each.key] == 0 ? 2 : 1   # the inactive color serves as the backup priority
}

Refer to the official docs for Front Door weight/priority semantics (weight range, priority failover); the example sets the inactive color to lower priority so it receives no normal traffic but can act as a fallback if the active color's health probe fails.

Lab 6: Try three replacement strategies and a blue-green switch on the dev network (about 9 minutes)

Prepare a directory and read the network and platform layer outputs:
mkdir -p ~/myapp-infra/live/dev/60-zero-downtime && cd ~/myapp-infra/live/dev/60-zero-downtime
cp ../30-app/main.tf /tmp/30app.bak   # for reference only, do not modify 30-app
cat > base.tf <<'EOF'
terraform {
  backend "s3" { key = "dev/60-zero-downtime/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
    local  = { source = "hashicorp/local",  version = "~> 2.9" }
  }
}
provider "docker" {}
locals {
  state_backend = {
    bucket = "tfstate", region = "us-east-1", endpoints = { s3 = "http://localhost:9000" }
    use_path_style = true, skip_credentials_validation = true, skip_requesting_account_id = true
    skip_metadata_api_check = true, skip_region_validation = true
  }
  net   = data.terraform_remote_state.network.outputs.network_name
  redis = data.terraform_remote_state.platform.outputs.redis_host
}
data "terraform_remote_state" "network" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "dev/10-network/terraform.tfstate" })
}
data "terraform_remote_state" "platform" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "dev/20-platform/terraform.tfstate" })
}
resource "docker_image" "app" {
  for_each     = toset(["myapp:1.0", "myapp:1.1"])
  name         = each.key
  keep_locally = true
}
resource "docker_image" "nginx" {
  name         = "nginx:1.29-alpine"
  keep_locally = true
}
EOF
A. Default replacement (delete then create): single replica, fixed name, with a static nginx behind it:
cat > rolling.tf <<'EOF'
variable "image" {
  type    = string
  default = "myapp:1.0"
}
variable "cbd" {
  type    = bool
  default = false
}

resource "docker_container" "zd" {
  name  = "myapp-zd"                                   # fixed name
  image = docker_image.app[var.image].image_id
  env   = ["APP_ENV=dev", "REDIS_HOST=${local.redis}"]
  networks_advanced {
    name    = local.net
    aliases = ["myapp-zd-svc"]
  }
  healthcheck {
    test     = ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:5000/healthz')"]
    interval = "2s"
    retries  = 3
  }
  wait = true
}

resource "docker_container" "zd_lb" {
  name  = "myapp-zd-lb"
  image = docker_image.nginx.image_id
  networks_advanced { name = local.net }
  ports {
    internal = 80
    external = 8086
  }
  upload {
    file    = "/etc/nginx/conf.d/default.conf"
    content = <<-EOT
      server {
        listen 80;
        resolver 127.0.0.11 valid=2s ipv6=off;
        set $u http://myapp-zd-svc:5000;
        location / { proxy_pass $u; proxy_next_upstream error timeout http_502; }
      }
    EOT
  }
}
EOF
terraform init -input=false -backend-config=../../backend.s3.hcl && terraform apply -auto-approve
# Open another terminal and run the load probe (every 0.2 seconds):
while true; do curl -s -o /dev/null -m 1 -w "%{http_code}\n" localhost:8086/; sleep 0.2; done | tee /tmp/zd.log
# Back in the first terminal: upgrade the image
terraform apply -auto-approve -var image=myapp:1.1 | grep -E "Destroying|Creating|Destruction|Creation"
# Stop the probe, then tally the results
sort /tmp/zd.log | uniq -c
docker_container.zd: Destroying... [id=7c1f…]
docker_container.zd: Destruction complete after 1s
docker_container.zd: Creating...
docker_container.zd: Creation complete after 7s [id=91ab…]
    412 200
     38 502

In the plan, this container shows -/+ resource "docker_container" "zd" (forces replacement). 502 errors appear in the gap after the old one is deleted and before the new one is healthy.

B. cbd + fixed name: observe the name conflict: in docker_container.zd add lifecycle { create_before_destroy = true }, then terraform apply -auto-approve -var image=myapp:1.0:
docker_container.zd: Creating...
│ Error: Unable to create container: Error response from daemon: Conflict. The container name "/myapp-zd" is already in use by container "91ab…". You have to remove (or rename) that container to be able to reuse that name.

Create-before-destroy requires old and new to exist at the same time, which a fixed name cannot do. The state is not corrupted at this point: the old container is still there, and the new container creation fails.

C. cbd + unique name + health wait + drain: change the name to a unique name that includes the image hash, and add a drain wait on destroy:
# Modify docker_container.zd in rolling.tf:
  name  = "myapp-zd-${substr(docker_image.app[var.image].image_id, 7, 12)}"   # image changes → name changes
  ...
  lifecycle { create_before_destroy = true }

  provisioner "local-exec" {
    when    = destroy
    command = "sleep 4"      # drain: wait for nginx's DNS cache (valid=2s) to expire and in-flight requests to finish
  }
terraform apply -auto-approve -var image=myapp:1.0     # first converge to the unique name
: > /tmp/zd.log   # clear the log and restart the probe
terraform apply -auto-approve -var image=myapp:1.1 | grep -E "Destroying|Creating|deposed|complete"
sort /tmp/zd.log | uniq -c
docker_container.zd: Creating...
docker_container.zd: Creation complete after 6s [id=5e0d…]
docker_container.zd (deposed object 3b2a9c1f): Destroying... [id=c44e…]
docker_container.zd (deposed object 3b2a9c1f): Provisioning with 'local-exec'...
docker_container.zd (deposed object 3b2a9c1f): Destruction complete after 5s
    455 200

Note the deposed object: this is the old object that has been staged and is waiting to be destroyed. The new container is healthy (wait = true) before the destroy phase begins; the drain wait lets nginx's DNS cache expire, so every request returns 200.

D. Blue-green: two sets of containers + a reloadable LB:
cat > bluegreen.tf <<'EOF'
variable "active_color" {
  type    = string
  default = "blue"
  validation {
    condition     = contains(["blue", "green"], var.active_color)
    error_message = "active_color must be blue or green."
  }
}
variable "versions" {
  type    = map(string)
  default = { blue = "myapp:1.0", green = "myapp:1.1" }
}

locals {
  slots = { for c, img in var.versions : "${c}-0" => { color = c, image = img } }
}

resource "docker_container" "bg" {
  for_each = merge(local.slots, { for c, img in var.versions : "${c}-1" => { color = c, image = img } })
  name     = "myapp-bg-${each.key}"
  image    = docker_image.app[each.value.image].image_id
  env      = ["APP_ENV=dev", "APP_COLOR=${each.value.color}", "REDIS_HOST=${local.redis}"]
  networks_advanced {
    name    = local.net
    aliases = ["myapp-bg-${each.value.color}"]
  }
  healthcheck {
    test     = ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:5000/healthz')"]
    interval = "2s"
    retries  = 3
  }
  wait = true
}

resource "local_file" "bg_conf" {
  filename = "${path.module}/nginx/bg.conf"
  content  = <<-EOT
    server {
      listen 80;
      resolver 127.0.0.11 valid=2s ipv6=off;
      set $u http://myapp-bg-${var.active_color}:5000;
      location / { proxy_pass $u; }
      location = /color { return 200 "${var.active_color}\n"; }
    }
  EOT
}

resource "docker_container" "bg_lb" {
  name  = "myapp-bg-lb"
  image = docker_image.nginx.image_id
  networks_advanced { name = local.net }
  ports {
    internal = 80
    external = 8087
  }
  volumes {
    host_path      = abspath("${path.module}/nginx")
    container_path = "/etc/nginx/conf.d"
    read_only      = true
  }
  depends_on = [local_file.bg_conf, docker_container.bg]
}

# Traffic switch: config change → graceful reload (does not replace the LB container, connections are not interrupted)
resource "terraform_data" "bg_switch" {
  triggers_replace = [local_file.bg_conf.content_sha256]
  provisioner "local-exec" {
    command = "docker exec myapp-bg-lb nginx -t && docker exec myapp-bg-lb nginx -s reload"
  }
  depends_on = [docker_container.bg_lb]
}
EOF
terraform apply -auto-approve
for i in 1 2 3; do curl -s localhost:8087/; done
myapp v1.0 env=dev color=blue host=myapp-bg-blue-0… hits=101
myapp v1.0 env=dev color=blue host=… hits=102
myapp v1.0 env=dev color=blue host=… hits=103
Switch to green and verify zero downtime and rollback capability:
: > /tmp/bg.log
(while true; do curl -s -m 1 localhost:8087/ | awk '{print $2, $4}' ; sleep 0.2; done >> /tmp/bg.log) &
PROBE=$!
terraform plan -var active_color=green | grep -E "^  [~+-]|Plan:"
terraform apply -auto-approve -var active_color=green
sleep 3; kill $PROBE
uniq -c /tmp/bg.log
terraform apply -auto-approve -var active_color=blue    # rollback: within seconds
  ~ resource "local_file" "bg_conf" …(must be replaced)
-/+ resource "terraform_data" "bg_switch" …
Plan: 2 to add, 0 to change, 2 to destroy.
     23 v1.0 color=blue
     31 v1.1 color=green

The plan only touches the “config file + switch”; the four application containers and the LB container do not change — blue-green's risk is concentrated in one reviewable switch that can be rolled back within seconds. Note local_file 's content change in hashicorp/local appears as a replacement (this resource has no in-place update); this is harmless here.

Cleanup: terraform destroy -auto-approve (the network and Redis belong to other states and are unaffected — verify the blast radius again).

Case 1: Security group replacement causes full-site outage

Problem: Changing aws_security_group of description (ForceNew) triggers replacement; by default it deletes first and then creates, but the security group is still referenced by an ENI, so the delete hung for 15 minutes and then timed out; after someone manually detached it, service was interrupted. Fix: Switch the security group to name_prefix + cbd, with rules managed by separate aws_vpc_security_group_ingress_rule resources; the CI gate checks the plan for ["delete","create"]. Limitation: During cbd, old and new security groups coexist; watch the per-ENI security group quota.

Case 2: Azure Container Apps revision blue-green

Problem: The new version needs to be verified in production before shifting traffic. Fix: Enable multi-revision mode on the Container App, with Terraform managing the revision_suffix and the ingress traffic_weight block: deploy the new revision first at 0% weight and verify via its revision-specific FQDN, then set the weight to 100 in the “switch PR”. Limitation: Field names in the weight block (latest_revision,revision_suffix,percentage) follow the azurerm 5.x docs; frequent automated gradual traffic shifts are better handled by CLI/pipelines than by Terraform.

Case 3: Major database version upgrade

Problem: Changing engine_version from 15 to 17; the plan shows an in-place update, but the database is unavailable for 20 minutes during apply. Fix: Use RDS Blue/Green Deployments (the provider's blue_green_update { enabled = true } applies to partial change scenarios) or run it in a maintenance window; complete compatibility testing on the application side in advance; apply_immediately = false let the change land in a maintenance window. Limitations: Managed blue-green has requirements on engine and topology; there is still a brief connection interruption at the moment of switchover, so the application must be able to reconnect.

Common errors and fixes

Error: ... already exists / Conflict. The container name "/myapp-zd" is already in use (after enabling create_before_destroy)

Cause: The old and new objects must exist at the same time, but the name is fixed and unique.

Fix: usename_prefix, or add a value that changes with replacement to the name (image hash,random_id + keepers); resources that cannot be renamed should use blue-green or a maintenance window.

Error: Cycle: aws_launch_template.app, aws_autoscaling_group.app (destroy deposed …)

Cause: A cbd resource depends on a non-cbd resource, which is also being replaced, creating a conflicting ordering between delete-then-create and create-before-destroy (newer Terraform versions usually propagate cbd automatically, but some combinations still occur).

Fix: Explicitly set cbd on all related resources along the dependency chain; check whether you mistakenly used depends_on creating extra edges.

Error: Instance cannot be destroyed ... Resource aws_db_instance.main has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed.

Cause: A parameter change requires the database to be replaced — the protection mechanism is working as designed.

terraform plan -out=p && terraform show -json p | jq '.resource_changes[] | select(.address=="aws_db_instance.main") | .change.replace_paths'

Fix: Based on replace_paths find the attribute that triggers replacement; revert that change or switch to the managed upgrade process. Do not remove prevent_destroy just to get the apply to pass.

Error: timeout while waiting for container to become healthy (docker wait = true)

Cause: The new container's health check keeps failing (misconfiguration, unreachable dependency, wrong port), and the cbd flow stops at the “create” stage — the old container is still serving, which is a good thing.

docker ps -a --filter name=myapp-zd
docker inspect --format '{{json .State.Health}}' CONTAINER | jq

Fix: Correct the issue and re-apply; the failed new object is marked as tainted and will be replaced on the next apply.

After switching the DNS weighted records, a lot of traffic still hits the old environment

Cause: TTL caching, long-lived client connection pools, and resolvers that do not honor the TTL.

Fix: Lower the TTL in advance (for example, to 60 seconds 24 hours before the switch); keep the old environment until traffic drops to zero; prefer switching at the LB/Front Door layer rather than the DNS layer.

Command-line exercises
1. Force replacement without changing the code docker_container.zd, and first confirm the plan order.
terraform plan -replace=docker_container.zd
terraform apply -replace=docker_container.zd
2. List all resources to be replaced in a plan and their replacement order (cbd or default).
terraform show -json tf.plan | jq -r '.resource_changes[] | select(.change.actions|length==2) | "\(.address)\t\(.change.actions|join(","))"'
Scenario analysis
You need to replace an Azure VM that has a data disk attached and a fixed public IP bound with a new image; the business requires downtime of no more than 1 minute. How would you design this with Terraform?

Direct cbd is not feasible: a data disk can only attach to one VM, a public IP can only be associated with one NIC, and the VM name may collide. Approach: ① separate “state” from “compute”: keep the data disk and public IP as independent resources (not replaced with the VM); ② use blue-green: the new VM (with a different name) starts with the new image and is configured first; ③ within the switchover window: stop the old VM → detach the data disk → attach it to the new VM → associate the public IP with the new NIC (or better: put an LB in front and switch the backend pool); ④ split these steps into 2–3 small applies (or use active_color variables to control the associations), with every step rollback-able; ⑤ long-term improvement: make it stateless with VMSS/LB and move data to managed storage.

Verified instructional videos

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · explanation of lifecycle meta-arguments; for the combination of blue-green and draining, follow this lesson

No verified video was found that specifically explains the create_before_destroy replacement timing and Terraform blue-green switching.

Official docs

Video storyboard (about 100 seconds)

This courseware cannot directly generate video/MP3 files, so a storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: on the timeline, the old container disappears, there is a blank gap of a few seconds, and then the new container appears; requests in the gap turn into red 502s.
Narration: Terraform deletes first and then creates by default, so there is a gap in between.
Shot 2 · 25–50s
Visual: the new container tries to use the same name and a Conflict pops up; after adding a hash to the name, it succeeds and both coexist.
Narration: create-before-destroy requires old and new to coexist, so names must be unique.
Shot 3 · 50–75s
Visual: after the new container shows a green healthy indicator, the old container is marked as deposed, and after a few seconds of draining it disappears; the request bar stays green throughout.
Narration: wait for health, update dependents, drain, then delete the old object.
Shot 4 · 75–100s
Visual: two sets of blue-green containers, with a switch in the middle flipped from blue to green and then back to blue.
Narration: blue-green concentrates the risk in one switch; both switching and rollback only require changing one variable.
or score ≥ 70% on the “Quiz”

Module 7 · Importing existing resources and migration

47:00 – 54:00 · Turn “wild” resources built via ClickOps into “domesticated” resources with code, state, and review
7 minimport block 1.5 · for_each 1.7 · import inside a module 1.16list block / terraform query 1.14+★★★★☆
Learning objectives
  • Use declarative import blocks (reviewable, plannable, and batchable for_each) in place of imperative terraform import.
  • Use terraform plan -generate-config-out=FILE to generate initial code, then tidy it into code that follows module conventions until the plan shows zero changes.
  • Master the complete ClickOps migration process (inventory → grouping → import → convergence → lock out manual changes), and understand the Terraform 1.14 list block and terraform query how to combine “inventory” and “generating import code” into one step.
Prerequisites: Module 2's module interfaces and module 3's state boundaries. Importance:★★★★☆

What: three import methods

MethodVersionMechanismProsCons
terraform import ADDR ID (command)EarlyWrites to state immediately; requires a hand-written resource block firstSimpleNot reviewable, one at a time, cannot preview the plan in CI
import { to = ADDR id = "…" } (block)1.5+ (for_each 1.7+, inside modules 1.16+)Part of the plan: the provider ImportResourceState → ReadResource → compares with configurationCan be PR-reviewed, batched, previewed in plan, and applied together with other changesNeed to know each resource's import ID
list block + terraform query1.14+In *.tfquery.hcl , declare the resource types and filters to discover; the provider lists matching resources; -generate-config-out Directly generates import and resource blocks“inventory + generate” in one step, with no need to look up IDs one by oneRequires the provider to implement list resources (aws and azurerm already have many; kreuzwerker/docker 4.7.0 does not yet); some list resources are still marked beta

Why: why take over existing resources

  • Manually created resources have no change history and no review, and cannot be replicated in other environments; during disaster recovery rebuilds, “nobody remembers how it was clicked together”.
  • When referencing Terraform resources, you can only hardcode IDs.
  • Compliance requires that “infrastructure changes be traceable”.

How: ClickOps → Terraform migration process

  1. Inventory: List resources by resource group / tag / account (terraform query,az resource list, AWS Resource Explorer,docker ps -a), and mark owners and importance.
  2. Group into state: Following module 3's rules, decide which stack each resource belongs to (network/platform/application); do not import everything into one state.
  3. Write import blocks: one per resource (or for_each batched with for_each), first import into “flat” resource addresses.
  4. Generate and tidy the configuration:plan -generate-config-out → remove read-only/default-value attributes, change to reference variables and other resources, and move into modules as needed (using moved blocks to move from flat addresses to module addresses).
  5. Converge to zero diff: Keep running plan until only “N to import, 0 to add, 0 to change, 0 to destroy” remains, then apply.
  6. Lock out manual changes: Revoke console write permissions, enable drift detection (lesson 5), and delete completed import blocks (keeping them is harmless, but makes the code messier).

When

  • Resource will persist long-term and needs changes → import.
  • Resource is referenced read-only (for example, another team's VNet) → do not import; read it via a data source or parameter store (to avoid two states managing the same resource).
  • Resource is about to be decommissioned → do not import; just clean it up.
  • Large numbers of existing Azure resources → you can also evaluate Microsoft's aztfexport (Azure Export for Terraform) for bulk export, but the generated code still needs tidying.
Common misconceptions① “It's normal for the plan to show a diff after import; just apply” — a diff means Terraform will change the real resource, so the code must first describe the current state, and zero diff must be confirmed before anything else. ② “The same resource can be imported into two states” — this causes two stacks to overwrite each other; there must be exactly one owner. ③ “Generated configuration can be used as-is” — generated code contains many default values and computed attributes, and does not use variables and references; it is only a starting point. ④ “import creates resources” — it does not; import only writes an existing object into state.

Flowchart: what the import block does during plan

import blockto + id ImportResourceStateprovider: ID → object skeleton ReadResourceCall API to read all attributes Has a resource block? PlanResourceChangeconfig vs current state → diff No → need-generate-config-out Generate configuration: GenerateResourceConfiguration (from 1.14, providers can produce more precise generation results)→ generated.tf (resource block with hardcoded current values) → manual tidy-up → plan again until 0 change
Figure 7-1 import is part of the plan: first read the real object, then compare with the configuration; when there is no configuration, Terraform can generate it

Flowchart: terraform query (1.14+)

discover.tfquery.hcllist "aws_instance" "web" {…} terraform queryprovider lists matching resources (including identity) -generate-config-outimport + resource blocks tidy → plan → applySame as the import block flow
Figure 7-2 query turns “finding IDs one by one” into “declaring what to find”; from 1.17, query results can also be passed to Terraform Policy for evaluation

Animation: one ClickOps migration pipeline

Plays the process of taking over three manually created Docker resources (network, Redis, nginx) into Terraform. Each step shows the real command, the provider RPC, and a plan summary. Check “someone manually changed the port during migration” to see how drift surfaces in the plan.

Ready.
$ docker ps -a --filter label!=managed-by=terraform

Core commands and syntax

Command / syntaxPurposeNotes
import { to = docker_network.legacy id = "…" }Declare importid must be known at plan time; expressions are allowed
import { for_each = local.m to = x.y[each.key] id = each.value }Batch import (1.7+)The target resource also needs for_each
terraform plan -generate-config-out=generated.tfGenerate configuration for imports without a resource blockThe file must not exist; the output must be tidied afterwards
terraform queryRun *.tfquery.hcl list blocks (1.14+)-generate-config-out=PATH,-json,-var; from 1.17 -policies GA
terraform validate -queryOffline validation of query files (1.14+)Use in CI
moved { from = … to = … }Rename / move into module, no recreationEssential when tidying import code
terraform state show ADDRView attributes after importCompare with generated code

AWS: use list blocks to discover and generate import code (Terraform 1.14+, aws 6.x)

list "aws_instance" "legacy_web" {
  provider = aws
  config {
    filter {
      name   = "tag:app"
      values = ["myapp"]
    }
    filter {
      name   = "instance-state-name"
      values = ["running", "stopped"]
    }
  }
}

list "aws_security_group" "legacy" {
  provider = aws
}
terraform validate -query
terraform query                                     # first, see what was found
terraform query -generate-config-out=to-import/legacy.tf
terraform plan                                      # expected: N to import, 0 to add/change/destroy

The aws provider docs for aws_instance list resources note: by default, instances managed by Auto Scaling and instances in terminated/shutting-down state are excluded (include_auto_scaled can be changed); some list resources are still marked as beta. -generate-config-out The specified file must not already exist.

Azure: list blocks (azurerm 5.x already provides many list resources)

list "azurerm_linux_virtual_machine" "legacy" {
  provider = azurerm
  # For available filter parameters (such as resource group), refer to the registry docs for that list resource
}

Imperative import (only for one-off fixes)

terraform import 'docker_container.legacy["web"]' "$(docker inspect -f '{{.Id}}' legacy-web)"

Lab 7: Import the manually created network and containers into Terraform and converge to zero diff (about 8 minutes)

Simulate ClickOps: someone manually built a legacy environment in the “console” (here, the docker CLI):
docker network create --subnet 172.30.9.0/24 legacy-net
docker run -d --name legacy-redis --network legacy-net --restart unless-stopped redis:7-alpine
docker run -d --name legacy-web --network legacy-net --restart unless-stopped -p 8099:80 nginx:1.29-alpine
docker ps --filter name=legacy- --format '{{.Names}}\t{{.Image}}\t{{.Ports}}'
legacy-web     nginx:1.29-alpine   0.0.0.0:8099->80/tcp
legacy-redis   redis:7-alpine
Inventory and generate import blocks (the docker provider has no list resources, so inventory with the CLI; in the cloud you can use terraform query):
mkdir -p ~/myapp-infra/live/dev/70-legacy && cd ~/myapp-infra/live/dev/70-legacy
cat > versions.tf <<'EOF'
terraform {
  backend "s3" { key = "dev/70-legacy/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}
EOF
{
  echo "import {"
  echo "  to = docker_network.legacy"
  echo "  id = \"$(docker network inspect -f '{{.Id}}' legacy-net)\""
  echo "}"
  for c in redis web; do
    echo "import {"
    echo "  to = docker_container.legacy_$c"
    echo "  id = \"$(docker inspect -f '{{.Id}}' legacy-$c)\""
    echo "}"
  done
} > imports.tf
cat imports.tf
import {
  to = docker_network.legacy
  id = "5b9d0c3e…"
}
import {
  to = docker_container.legacy_redis
  id = "e41f7a2c…"
}
import {
  to = docker_container.legacy_web
  id = "0c88b1d4…"
}
Generate configuration:
terraform init -input=false -backend-config=../../backend.s3.hcl
terraform plan -generate-config-out=generated.tf
wc -l generated.tf
docker_network.legacy: Preparing import... [id=5b9d0c3e…]
docker_container.legacy_web: Preparing import... [id=0c88b1d4…]
...
Plan: 3 to import, 0 to add, 0 to change, 0 to destroy.
╷
│ Warning: Config generation is experimental
│ Generating configuration during import is currently experimental, and the generated configuration format may change in future versions.
╵
Terraform has generated configuration and written it to generated.tf.
   142 generated.tf

If an attribute causes a plan error after generation (for example, mutually exclusive parameters were both generated, or it is a read-only attribute), follow the error message to delete that attribute from generated.tf and plan again. The exact warning wording depends on the version you use.

Tidy the code: rewrite generated.tf as readable main.tf— keep only meaningful parameters, change the image to a reference, and change the network to a resource reference instead of a hardcoded name:
resource "docker_network" "legacy" {
  name = "legacy-net"
  ipam_config { subnet = "172.30.9.0/24" }
}

resource "docker_container" "legacy_redis" {
  name    = "legacy-redis"
  image   = "redis:7-alpine"      # generated results are usually a sha256 image ID; after changing to the name, check the plan
  restart = "unless-stopped"
  networks_advanced { name = docker_network.legacy.name }
}

resource "docker_container" "legacy_web" {
  name    = "legacy-web"
  image   = "nginx:1.29-alpine"
  restart = "unless-stopped"
  networks_advanced { name = docker_network.legacy.name }
  ports {
    internal = 80
    external = 8099
  }
}
mv generated.tf /tmp/generated.tf.bak
terraform plan

In practice, the first plan almost always shows a diff (for example, changing the image field from an ID to a name causes “forces replacement”, default value differences,must_run,log_driver etc.). Compare each item against /tmp/generated.tf.bak, change properties that would cause replacement back to their current values (for example, image set it to the generated sha256 ID, or use the docker_image resource's image_id), and harmless changes may be accepted as in-place updates. Goal: Plan: 3 to import, 0 to add, 0 to change, 0 to destroy.

Apply and verify:
terraform apply -auto-approve
terraform state list
terraform plan -detailed-exitcode; echo "exit=$?"     # 0 = no changes
Apply complete! Resources: 3 imported, 0 added, 0 changed, 0 destroyed.
docker_container.legacy_redis
docker_container.legacy_web
docker_network.legacy
No changes. Your infrastructure matches the configuration.
exit=0
Refactor to for_each and keep zero changes using a moved block: change the two containers to resource "docker_container" "legacy" { for_each = { redis = {…}, web = {…} } … }, and add:
moved {
  from = docker_container.legacy_redis
  to   = docker_container.legacy["redis"]
}
moved {
  from = docker_container.legacy_web
  to   = docker_container.legacy["web"]
}

The plan should show “has moved to …” with 0 changes. Afterwards, delete imports.tf (the import is complete).

Simulate drift detection: docker rm -f legacy-web && docker run -d --name legacy-web --network legacy-net -p 8098:80 nginx:1.29-alpine (someone manually changed the port), then terraform plan— this will show that legacy-web needs to be rebuilt (ID changed / different port). This is why manual access must be revoked after migration. Finally, clean up: terraform destroy -auto-approve.

Case 1: Taking over 400 manually created Azure resources

Problem: In the early days, all projects were created through the portal, spanning 6 resource groups. Approach:① Use az resource list (or terraform query of the azurerm list resources) to export an inventory, and split it into three states by network/platform/application; ② one PR per state, where the PR contains only import blocks plus tidied code, and the review criterion is “0 to add/change/destroy”; ③ after import is complete, revoke portal write permissions to an “emergency access” group and enable daily drift detection. Limitations: Some resources (such as certain child resources and hidden resources automatically created by the portal) need to be imported separately or accepted as unmanaged; for import ID formats, refer to the Import section at the end of each resource's docs.

Case 2: Migrating from the terraform import command to import blocks

Problem: Operations used imperative import to fix state, bypassing review; one time a wrong ID was imported, bringing a test database into the production state. Approach: All imports must be submitted as import blocks in a PR, with CI plan showing the “import” action; running write commands against production state locally is prohibited. Limitations: From 1.16, import blocks can also be written inside modules; module authors can use this to provide the ability to “take over existing resources”, but note that IDs differ between callers.

Case 3: Ensuring “no recreation” when migrating to a modular structure

Problem: The flat code after import needs to be moved into modules/web-service. Approach: Within the same state, use moved blocks (from docker_container.legacy["web"] to module.app.docker_container.app[0]); across states, use removed (destroy = false) + new stack import (module 3). Each step requires that the plan has no destroy. Limitations: Default values of resource attributes in modules may differ from the current state; you need to add optional parameters to the module to express “legacy differences”, or schedule a planned convergence change.

Common errors and fixes

Error: Cannot import non-existent remote object ... While attempting to import an existing object to "docker_container.legacy_web", the provider detected that no object exists with the given id.

Cause: Wrong ID (the ID changed after the container was recreated, a short ID/name was used while the provider requires the full ID, or the cloud resource ID format is wrong).

docker inspect -f '{{.Id}}' legacy-web

Fix: Use the ID format specified in the Import section of the resource docs.

Error: Resource already managed by Terraform ... Terraform is already managing a remote object for docker_container.legacy_web.

Cause: The address is already in state (the import is complete but the import block was kept and the ID changed, or the import was repeated).

Fix: Delete the completed import block; if you really need to rebind the object, first terraform state rm then import (with caution).

Error: Target generated configuration file already exists

Cause:-generate-config-out The specified file already exists, and Terraform will not overwrite it.

Fix: Use a different file name or move the old file out of the way first.

Plan after import: # docker_container.legacy_web must be replaced (image forces replacement)

Cause: The code describes something different from the current state, and this attribute is ForceNew.

terraform state show docker_container.legacy_web | grep -E 'image|ports' -A2

Fix: Change the code to match the current state in state; attributes that need changing should be left for a separate change after import completes.

Error: Unsupported block type ... Blocks of type "list" are not expected here / terraform: unknown command "query"

Cause: Terraform is below 1.14, or the list block was written into the .tf file (it should be placed in *.tfquery.hcl ); the provider also errors if it does not support that list resource.

Fix: Upgrade to 1.14+ (this lesson's baseline is 1.17.2); check the file extension; confirm provider support under the “List Resources” category in the registry docs.

Command-line exercises
1. Use a for_each import block to import all Docker containers with team=web labeled Docker containers (IDs generated by the shell into tfvars).
docker ps -a --filter label=team=web --format '{{.Names}} {{.ID}}' | \
  awk 'BEGIN{print "legacy_ids = {"} {printf "  \"%s\" = \"%s\"\n",$1,$2} END{print "}"}' > legacy.auto.tfvars
# Note: docker ps shows short IDs, but import needs full IDs; you can use --no-trunc instead
cat > imports.tf <<'EOF'
variable "legacy_ids" { type = map(string) }
import {
  for_each = var.legacy_ids
  to       = docker_container.web[each.key]
  id       = each.value
}
EOF
2. In CI, assert that “an import PR must not contain any add/change/destroy”.
terraform plan -out=tf.plan >/dev/null
terraform show -json tf.plan | jq -e '[.resource_changes[] | select(.change.actions != ["no-op"] and .change.actions != ["read"])] | length == 0' \
  || { echo "A real change appeared in the import PR"; exit 1; }

The actions for purely imported resources are ["no-op"], and carry a change.importing field.

Scenario analysis
A team wants to import a shared hub VNet (maintained by the network team, already in the network team's state) into its own application state, so it can be referenced “conveniently”. How would you answer?

No: a resource can have only one state owner; otherwise the two stacks overwrite each other (one apply rolls back the other's changes), and a destroy could even delete the shared network. The application stack should read the hub's IDs through data sources (azurerm_virtual_network), parameter store, or remote_state; changes that must happen on the hub side (for example, the hub end of a peering) are managed by the network team's stack, and the application team submits a PR to the network repo.

Verified instructional videos

▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · basic explanation of state and import (recorded before import blocks and terraform query; for the new syntax, follow this lesson)

No verified video was found that specifically explains the import block + -generate-config-out or terraform query verified video.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3 files, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: in the console, the mouse clicks out a bunch of resources, and the “change log” beside it is blank.
Narration: manually created resources have no code, no review, and cannot be replicated.
Shot 2 · 20–45s
Visual: the import block is like a “claim form”; the plan shows 3 to import; the provider reads the real object.
Narration: import blocks are part of the plan; they can be reviewed and batched.
Shot 3 · 45–70s
Visual: generated.tf is very long and gets trimmed into a concise main.tf; the diffs in the plan disappear one by one until zero.
Narration: generated code is only a starting point; the work is done only when tidying brings it to zero changes.
Shot 4 · 70–90s
Visual: terraform query scans the cloud account and automatically outputs import code; the console's write permission button turns gray.
Narration: from version 1.14 onward you can use query to discover resources; after migration is complete, remember to revoke manual permissions.
or score ≥ 70% on the “Quiz”

Module 8 · Comprehensive architecture review

54:00 – 60:00 · Use a checklist to find gaps and failure mode analysis to set priorities — the output of a review is “risks and actions”, not “pass/fail”
6 minReview checklist · FMEA · troubleshooting tree★★★★★
Learning objectives
  • Use an IaC architecture review checklist covering 8 dimensions (layout, modules, state, identity, secrets, change safety, import/drift, operations).
  • Rank risks using failure mode and effects analysis (FMEA: severity × occurrence × detection difficulty = RPN) and write mitigation measures.
  • Use the interactive troubleshooting tree to locate typical faults in multi-state architectures: empty output read, lock conflicts, unexpected replacement, permission denied, import drift.
Prerequisites: Modules 1–7. Importance:★★★★★

What: IaC architecture review checklist (8 dimensions × key questions)

DimensionKey questionsGood evidenceRed flags
1 LayoutHow are environments isolated? Are directory/key conventions documented?Per-environment directories + shared backend file; ADR records the choiceprod uses CLI workspaces; key naming is ad hoc
2 ModulesAre modules small and focused? Are versions pinned?Leaf modules + composition modules; ?ref=vX.Y.Z; validationGod modules; ref=main; submodules containing provider blocks
3 StateBlast radius? Cross-stack reference method? Dependency direction?Network/platform/application layering; only reference downward; stateful resources use prevent_destroyA single state with thousands of resources; circular references; remote_state across trust domains
4 Identity and multi-accountWhat identity does each state use? Is prod in a separate account/subscription?OIDC + per-layer roles; check Assert account; SCP/Policy as a safety netLong-lived access keys; same service principal for all environments
5 SecretsAre there plaintext secrets in state/plan?ephemeral + write-only; managed passwords; state encryption and least-privilege read accesssensitive outputs shared via remote_state; plan artifacts are public
6 Change safetyIs replacement zero-downtime? How are high-risk deletions blocked?cbd + unique name + health wait; plan JSON gate; blue-green switchNobody reviews the plan; DB parameter changes applied directly
7 Import and driftAre existing resources taken over? How are manual changes detected?import block PRs; daily drift detection; read-only consoleSame resource managed by two states; console changes made freely
8 OperationsState backup and recovery? Can the DR region apply independently? Upgrade cadence?Version control + cross-region replication; drill records; provider upgrade processState only in the primary region; recovery never drilled

Why: failure mode analysis (FMEA)

A checklist tells you “whether it has been done”; FMEA tells you “which to do first”. Score each failure mode: S (severity 1–10),O (occurrence probability 1–10),D (difficulty of detection 1–10; the harder to detect, the higher the score),RPN = S × O × D. Handle high-RPN items first; any item with S ≥ 9 must have mitigation regardless of its RPN.

Failure modeImpactSODRPNMitigation
Wrong workspace/key selected; dev parameters applied to prodProduction outage945180Directory-based layout; check asserts account; prod writable only via pipeline
Refactor missing moved block; DB/DNS destroyed and recreatedData loss1036180prevent_destroy; plan JSON deletion gate; separate state
Plaintext secrets in state read by downstream consumersCredential leak868384write-only / managed passwords; parameter store; minimize state read permissions
Name conflict / gap during replacementBrief outage65390cbd + unique name + health wait
State unreadable when the primary region failsCannot perform DR changes827112Cross-region state replication; split state by region; drills
Upper layer reads stale outputs from a lower layerConfiguration error556150“publish the interface before consuming it”; run pipelines in layer order
Manual change causes driftNext apply reverts the manual fix665180drift detection; read-only console; write emergency changes back to code

How: how to run the review meeting

  1. Before the meeting: the author submits an architecture diagram (like Figure 1-1/3-1), directory tree, state list, identity matrix, and one real plan output.
  2. During the meeting: go through the checklist by 8 dimensions; for each red flag, record the failure mode and score S/O/D.
  3. After the meeting: produce a “risk register” (failure mode, RPN, owner, due date) and write it into docs/adr/.

When

  • Before creating a new repo / launching a new product; when introducing a new account/region; before a major provider upgrade (for example, azurerm 4 → 5); after a major incident postmortem.
Common misconceptions① “Review = code style check” — style is left to terraform fmt, tflint; architecture review focuses on boundaries, identity, and failure modes. ② “Passing review means it's safe” — the output of a review is a ranked list of risks and action items, and risks need ongoing tracking. ③ “A low RPN can be ignored” — events with severity 10 need a safety net (backups, prevent_destroy) even if rare.

Review overview: myapp's target architecture

Code modules/ (SemVer, test)live/{dev,stage,prod}/ 10-network 20-platform 30-appCODEOWNERS tiered approvaldocs/adr/ risk register Pipeline (lesson 5) Change detection → affected directoriesplan in order 10→20→30plan JSON gate (delete/replace)State secrets scanPer-layer OIDC rolesDaily drift detection State storage 9 keys (3 environments × 3 layers)use_lockfile native lockVersioning + KMSCross-region replicationPer-key read/write authorization dev accountNetwork / platform / application stage accountSame structure prod account+ DR region · blue-green
Figure 8-1 The review scope is not just .tf files; it also includes pipelines, state storage, and account structure

Decision diagram: when you see “destroy” in the plan

Plan has a deletejq detects Is it an expected decommission? → apply after approval Address changed? → add a moved block ForceNew attribute changed? → replace_paths Stateless → cbd + unique name Stateful → stop! Managed upgrade/migration
Figure 8-2 “destroy” always needs an explanation

Interactive review: score your repo and generate a risk register

Check off the controls already satisfied by your repo (or the integrated lab repo), one by one. The tool calculates via FMEA: each unmet control raises the occurrence probability O or detection difficulty D of the corresponding failure mode, which changes the RPN. Results are sorted by RPN and next actions are listed (checkbox results are saved in this browser).

After checking, click “Calculate risk”.
The risk register will appear here

Review commands

CommandReview purpose
find live -name '*.tf' -path '*/live/*' | xargs grep -l 'backend "s3"'List all root modules
grep -rn 'ref=main\|ref=master' live modulesFind unpinned modules
grep -rln '^provider ' modules/Find provider blocks in submodules
grep -rn 'terraform_remote_state' live | awk -F/ '{print $2"/"$3}' | sort | uniq -cCross-stack dependency statistics
terraform show -json tf.plan | jq …Delete/replace gate
terraform state pull | jq '[.resources[].instances[]] | length'Resource count per state (blast radius)
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64Multi-platform hashes in lock file, to avoid CI/local inconsistencies
# One-click “architecture health check” script (run in the myapp-infra root directory)
echo "== root modules =="; find live -name main.tf -exec dirname {} \; | sort
echo "== unpinned module sources =="; grep -rn 'ref=main' live modules || echo "none"
echo "== provider blocks in submodules =="; grep -rln '^provider ' modules/ || echo "none"
echo "== resource count per state =="
for d in $(find live -name main.tf -exec dirname {} \; | sort); do
  n=$(terraform -chdir=$d state list 2>/dev/null | wc -l); echo "$n	$d"
done
echo "== do high-risk resources have prevent_destroy? =="; grep -rn 'prevent_destroy' modules live || echo "none (check databases/DNS)"
== root modules ==
live/dev/10-network
live/dev/20-platform
live/dev/30-app
...
== unpinned module sources ==
none
== provider blocks in submodules ==
none
== resource count per state ==
1	live/dev/10-network
3	live/dev/20-platform
5	live/dev/30-app

Lab 8: Run a 30-minute architecture review of your myapp-infra (first 3 steps completed in 5 minutes in class)

Collect materials: run the “architecture health check” script from the previous page; use tree -L 3 live modules to export the directory tree; generate a plan JSON for dev/30-app: terraform -chdir=live/dev/30-app plan -out=/tmp/app.plan && terraform -chdir=live/dev/30-app show -json /tmp/app.plan > /tmp/app.plan.json.
Go through the checklist: check items one by one in the interactive review on the “Animation” tab, then click “Calculate risk”.
Pick the top 3 RPN items and write actions: in docs/adr/0001-risk-register.md record (failure mode, RPN, mitigation, owner, due date).
Verify one mitigation: for example, add modules/redis to the data volume of lifecycle { prevent_destroy = true }, then in dev/20-platform run terraform plan -destroy, confirm it is blocked:
│ Error: Instance cannot be destroyed
│   on ../../../modules/redis/main.tf line 18:
│   18: resource "docker_volume" "data" {
│ Resource module.redis.docker_volume.data has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed.

After the demo, you may keep this setting (in the integrated lab, prod must keep it); to actually destroy dev, remove this line first.

Review with the troubleshooting tree: on the “Troubleshooting” tab, walk through the troubleshooting tree for any error you hit in this lesson's labs, and check whether it leads to the same root cause.

Case 1: The review uncovers a “hidden single point of failure”

Problem: The multi-account, multi-region design looked thorough, but the review found that all states were in one bucket in the primary region, and the pipeline runner was deployed only in the primary region. Approach: In the FMEA, this item had S=8, D=7; actions: cross-region state replication, a self-hosted runner in the DR region, and a DR apply drill every six months. Limitations: Drills require a change freeze window, and replication lag must be verified.

Case 2: Review of a major provider upgrade (azurerm 4 → 5)

Problem: azurerm 5.0 changed the default behavior of resource provider registration and removed/renamed some resources. Approach: Add an “upgrade” dimension to the review checklist: upgrade in dev first, run plan for each state and archive the differences; use resource_providers_to_register to explicitly list the RPs; observe in stage for a week before upgrading prod. Limitations: The module repo needs to support both old and new major versions for a period (version constraints >= 4.x, < 6.0) or publish a new major version.

Case 3: Review items driven by incident postmortems

Problem: After an accidental deletion incident, the team temporarily added a dozen rules, and in the end nobody followed them. Approach: Turn the rules into machine checks: plan JSON gates, tflint rules, Terraform Policy (1.17 GA), or OPA; review meetings only discuss architecture questions that machines cannot judge. Limitations: The policies themselves also need versioning and testing.

Common errors and fixes

In the pipeline, 30-app runs before 10-network and reports Unsupported attribute "network_name"

Cause: There is no dependency graph across states; the pipeline runs in parallel or in the wrong order.

Fix: Run in directory-prefix order; or use Terragrunt run --all / Stacks orchestration; interface changes follow “publish first, consume later”.

Two teams' applies keep “rolling back” each other's changes (the same resource appears in two states)

Cause: The same real resource was imported into two states.

for d in $(find live -name main.tf -exec dirname {} \;); do terraform -chdir=$d state pull | jq -r --arg d "$d" '.resources[].instances[].attributes.id // empty | "\(.)\t\($d)"'; done | sort | awk -F'\t' 'a[$1]++{print "duplicate:",$0}'

Fix: Determine a single owner; the other side removed { lifecycle { destroy = false } } then switches to reading it via a data source.

Error: Inconsistent dependency lock file ... provider registry.terraform.io/hashicorp/aws: locked version selection 6.40.0 doesn't match the updated version constraints "~> 6.70"

Cause: The version constraint was changed but did not update .terraform.lock.hcl.

Fix:terraform init -upgrade, commit the lock file; for multiple platforms use terraform providers lock -platform=….

Interactive troubleshooting decision tree: common issues in multi-state architectures

Covers six categories of symptoms: cross-stack references, state locks and backend, unexpected replacement/destruction, permissions, secrets, and import and drift. Select the symptom you see and narrow it down step by step.

Command-line exercises
1. Count which other state keys each root module under live/ references.
grep -rhoE 'key = "\$\{local.env\}/[0-9a-z-]+|key *= *"[a-z]+/[0-9a-z-]+' live | sort | uniq -c
2. Find all resources in the plan that will be destroyed and whose types are on the high-risk list.
terraform show -json tf.plan | jq -r '.resource_changes[] | select(.change.actions|index("delete")) | select(.type|test("db_instance|route53_zone|key_vault|kms_key|docker_volume")) | .address'
Scenario analysis
Review a design: “All environments in one state, using for_each = toset(["dev","stage","prod"]) to call the myapp-stack module, one provider configuration, and one apply deploys three environments.” List at least 4 problems and improvements.

① Blast radius: one apply or one bug affects prod at the same time; ② prod cannot get separate approval and credentials (one provider configuration = one identity = one account); ③ dev's experimental changes must be planned together with prod, blocking the release cadence; ④ lock granularity is too coarse, so teams wait on each other; ⑤ environment differences are written as each.key == "prod" ? … scattered through the code. Improvements: split root modules and state by environment directory, give prod a separate account and OIDC role; make differences explicit inputs; further split by layer into network/platform/application; the pipeline promotes the same module version through dev → stage → prod.

Verified instructional videos

▶
How To Structure Terraform Project (3 Levels) — Anton Putra
English · can serve as reference material for the review's “layout” dimension
▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · quick review of Terraform architecture (core / provider / state), suitable as background for review participants

Official docs

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3 files, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: the eight dimensions form a radar chart, with several dimensions visibly dented.
Narration: the review first uses the checklist to find the dented dimensions.
Shot 2 · 20–50s
Visual: each failure mode becomes a card showing severity, probability, and detection difficulty; multiplying the three gives the risk priority number, and the cards are sorted by size.
Narration: failure mode analysis tells us what to fix first.
Shot 3 · 50–75s
Visual: a red destroy appears in the plan, and the decision tree asks in turn: expected decommission? address change? immutable attribute? stateful?
Narration: every destroy must be explained.
Shot 4 · 75–90s
Visual: the risk register is written into the ADR folder, and action items are assigned owners and dates.
Narration: the output of a review is risks and actions, not a pass stamp.
or score ≥ 70% on the “Quiz”

Command cheat sheet

Terraform 1.17 · Infrastructure architecture · every code block can be copied with one click
After-class reference

Layout and backend

terraform -chdir=live/prod/30-app init -backend-config=../../backend.s3.hcl
terraform init -backend-config="key=prod/30-app/terraform.tfstate"
terraform init -migrate-state        # migrate state
terraform init -reconfigure          # only update the local backend cache
terraform workspace select -or-create pr-123
terragrunt run --all plan            # Terragrunt v1.x

Module interface

variable "redis" {
  type = object({ host = string, port = optional(number, 6379) })
}
variable "replicas" {
  type     = number
  default  = 2
  nullable = false
}
variable "old" { deprecated = "will be removed in v2" }     # 1.15+
output "ids" { type = list(string), value = … }    # 1.15+
source = "git::https://…/modules.git//web-service?ref=v1.3.0"
providers = { aws.primary = aws.cac1, aws.dr = aws.caw1 }

Cross-stack references

data "terraform_remote_state" "net" {
  backend = "s3"
  config  = merge(local.state_backend, { key = "prod/10-network/terraform.tfstate" })
  defaults = { owner = "unknown" }
}
data "aws_ssm_parameter" "vpc" { name = "/myapp/prod/network/vpc_id" }
data "azurerm_app_configuration_key" "vnet" { configuration_store_id = var.id, key = "myapp:prod:network:vnet_id" }

Multi-region / multi-account

provider "aws" { alias = "dr", region = "ca-west-1"
  assume_role { role_arn = "arn:aws:iam::222222222222:role/tf-deploy" } }
resource "aws_s3_bucket" "logs" {          # AWS 6.x
  for_each = toset(["ca-central-1", "ca-west-1"])
  region   = each.key
  bucket   = "myapp-logs-${each.key}"
}
provider "azurerm" { alias = "hub", subscription_id = var.hub_sub, features {} }
# azurerm 5.x: resource_providers_to_register = ["Microsoft.App"]

Secrets

ephemeral "random_password" "db" { length = 24 }
resource "aws_db_instance" "x" {
  password_wo         = ephemeral.random_password.db.result
  password_wo_version = var.pw_version
}
resource "azurerm_key_vault_secret" "s" {
  value_wo = ephemeral.random_password.db.result, value_wo_version = 1
}
variable "token" { ephemeral = true }
# audit: terraform state pull | grep -c "<secret>"

Zero downtime

lifecycle {
  create_before_destroy = true
  replace_triggered_by  = [terraform_data.cfg]
  prevent_destroy       = true
}
name_prefix = "myapp-prod-"
# terraform apply -replace='docker_container.zd'
# jq: .resource_changes[] | select(.change.actions == ["delete","create"])

Import and migration

cat > imports.tf <<'EOF'
import { to = docker_network.legacy  id = "<full-id>" }
EOF
terraform plan -generate-config-out=generated.tf
terraform validate -query            # 1.14+
terraform query -generate-config-out=to-import/x.tf
# moved { from = a.b  to = module.m.a.b }
# removed { from = a.b  lifecycle { destroy = false } }

Review and gates

terraform show -json tf.plan | jq -r '.resource_changes[] | select(.change.actions|index("delete")) | .address'
terraform show -json tf.plan | jq '.resource_changes[] | select(.change.replace_paths) | {address, replace_paths: .change.replace_paths}'
terraform plan -detailed-exitcode   # 0 no changes / 2 changes / 1 error
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64
terraform graph -type=plan | dot -Tsvg > g.svg

Note: in HCL, multiple arguments on the same line must be separated by newlines (object constructors { a = 1, b = 2 } can use commas); blocks written on one line in this cheat sheet to save space should be expanded across multiple lines in real code.

Quick troubleshooting table

Symptom / errorMost likely causeFirst step
Unsupported attribute (remote_state outputs)Wrong key / lower layer not applied / submodule output not exportedterraform -chdir=lower-layer output
Plan: N to add (resource clearly exists)Pointing to an empty state (workspace/key/-reconfigure)workspace show, check the key, do not apply
Error acquiring the state lockConcurrent runs or a leftover lockAfter confirming the holder, force-unlock
Variables not allowed (backend)backend cannot use variablespartial configuration -backend-config
Provider configuration not presentDeleted a provider/alias that still has resources, or a module with a providerRestore the provider, then destroy/migrate resources first
Invalid use of ephemeral valueephemeral value flows into a regular argumentUse *_wo or pass a secret ID
Conflict … name already in use (cbd)Fixed namename_prefix / hash suffix
Instance cannot be destroyedprevent_destroy blocks replacementCheck replace_paths
Cannot import non-existent remote objectWrong import IDGet the ID from the Import section of the resource docs
MissingSubscriptionRegistrationazurerm 5.x no longer auto-registers RPsresource_providers_to_register

Recommended configuration snippet: thin root module template

terraform {
  required_version = ">= 1.15, < 2.0"
  backend "s3" { key = "prod/30-app/terraform.tfstate" }      # other parameters come from ../../backend.s3.hcl
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}

provider "docker" {}

module "app" {
  source       = "../../../modules/web-service"               # module repo pattern: git::…?ref=v1.3.0
  env          = "prod"
  network_name = data.terraform_remote_state.network.outputs.network_name
  image        = var.image
  replicas     = 3
  http_port    = 8083
  redis = {
    host = data.terraform_remote_state.platform.outputs.redis_host
    port = data.terraform_remote_state.platform.outputs.redis_port
  }
}

variable "image" {
  type    = string
  default = "myapp:1.0"
}
output "url" { value = module.app.url }

Integrated lab + final quiz

Design a complete repository for myapp with dev / stage / prod environments × network / platform / application layers = 9 states, then deploy them in dependency order, promote versions, review, and clean up
After class ≈ 40 minutesIntegrate all modules
Scenario myapp is about to enter production operations. The architecture committee requires: the three environments use the same set of modules with different parameters; each environment is split into network/platform/application state layers stored in S3-compatible storage (local MinIO), with keys following <env>/<layer>/terraform.tfstate; upper layers may only read lower-layer outputs via remote_state; prod's stateful resources are protected by prevent_destroy protection; image versions are promoted dev → stage → prod; the deliverables include a risk register. All labs are completed on local Docker + MinIO, and the cloud-equivalent code is in modules 3–6.
Prerequisite check (modules 0, 2)
source ~/.tf-lab.env
cd ~/myapp-infra
ls modules/{network,redis,web-service}/main.tf modules/web-service/variables.tf
docker ps --filter name=tf-minio --format '{{.Names}} {{.Status}}'
docker image ls myapp --format '{{.Tag}} {{.ID}}'

If a module is missing, go back to the lab tabs of module 1 (network) and module 2 (redis, web-service) to create it.

Generate 9 thin root modules (modules 1, 3): environment parameters are centralized in one table, and each layer's code is generated by a script — this is “same code, different parameters”:
cat > live/envs.tsv <<'EOF'
# env	subnet_octet	http_port	replicas	image
dev	1	8081	1	myapp:1.0
stage	2	8082	2	myapp:1.0
prod	3	8083	3	myapp:1.0
EOF

remote_block() {   # $1=env $2=layer-name $3=data-name
cat <<EOF
data "terraform_remote_state" "$3" {
  backend = "s3"
  config = {
    bucket = "tfstate", key = "$1/$2/terraform.tfstate", region = "us-east-1"
    endpoints = { s3 = "http://localhost:9000" }, use_path_style = true
    skip_credentials_validation = true, skip_requesting_account_id = true
    skip_metadata_api_check = true, skip_region_validation = true
  }
}
EOF
}

header() {   # $1=env $2=layer
cat <<EOF
terraform {
  required_version = ">= 1.15, < 2.0"
  backend "s3" { key = "$1/$2/terraform.tfstate" }
  required_providers {
    docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
  }
}
provider "docker" {}
EOF
}

grep -v '^#' live/envs.tsv | while IFS=$'\t' read -r env oct port rep img; do
  d=live/$env
  { header $env 10-network
    cat <<EOF
module "network" {
  source = "../../../modules/network"
  env    = "$env"
  subnet = "172.30.$oct.0/24"
}
output "network_name" { value = module.network.network_name }
output "network_id"   { value = module.network.network_id }
output "subnet"       { value = module.network.subnet }
EOF
  } > $d/10-network/main.tf

  { header $env 20-platform; remote_block $env 10-network network
    cat <<EOF
module "redis" {
  source       = "../../../modules/redis"
  env          = "$env"
  network_name = data.terraform_remote_state.network.outputs.network_name
}
output "redis_host" { value = module.redis.host }
output "redis_port" { value = module.redis.port }
EOF
  } > $d/20-platform/main.tf

  { header $env 30-app; remote_block $env 10-network network; remote_block $env 20-platform platform
    cat <<EOF
variable "image" {
  type    = string
  default = "$img"
}
module "app" {
  source       = "../../../modules/web-service"
  env          = "$env"
  network_name = data.terraform_remote_state.network.outputs.network_name
  image        = var.image
  replicas     = $rep
  http_port    = $port
  redis = {
    host = data.terraform_remote_state.platform.outputs.redis_host
    port = data.terraform_remote_state.platform.outputs.redis_port
  }
}
output "url" { value = module.app.url }
EOF
  } > $d/30-app/main.tf
done
terraform fmt -recursive live
find live -name main.tf | sort

dev/10-network, dev/20-platform, and dev/30-app were already deployed in modules 1 and 3; the regenerated code is equivalent to before (same addresses), and subsequent plans should show No changes or only harmless differences.

Add guardrails for prod (modules 5, 6, 8): prod's Redis data volume must not be destroyed, and the prod root module asserts that the target Docker host is correct:
cat >> live/prod/20-platform/main.tf <<'EOF'

# Guardrail: prevent the prod platform layer from running on the wrong Docker host (cloud equivalent: assert account/subscription ID)
data "docker_network" "bridge" { name = "bridge" }
check "expected_host" {
  assert {
    condition     = data.docker_network.bridge.driver == "bridge"
    error_message = "Target Docker host is abnormal; please confirm DOCKER_HOST."
  }
}
EOF
# Add optional destroy protection to the redis module (lifecycle cannot use variables, so make it one of two resources)
grep -n 'resource "docker_volume"' modules/redis/main.tf

lifecycle.prevent_destroy Only accepts literals and cannot be controlled by variables. Common practice: set it in the module to true (temporarily removed when dev needs destroying), or in prod use removed/import a means other than that, such as a CI gate that rejects any prod/20-platform destroy plan for. This lab chooses to hardcode in the module prevent_destroy = true (already demonstrated in the module 8 lab), and explain in the cleanup step how to remove it.

Deploy all 9 states in dependency order (modules 1, 3):
for layer in 10-network 20-platform 30-app; do
  for env in dev stage prod; do
    echo "=== $env/$layer ==="
    terraform -chdir=live/$env/$layer init -input=false -backend-config=../../backend.s3.hcl >/dev/null
    terraform -chdir=live/$env/$layer apply -auto-approve -input=false | tail -1
  done
done
for p in 8081 8082 8083; do curl -s localhost:$p/; done
=== dev/10-network ===
No changes. Your infrastructure matches the configuration.
=== stage/10-network ===
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
...
myapp v1.0 env=dev color=none host=… hits=42
myapp v1.0 env=stage color=none host=… hits=1
myapp v1.0 env=prod color=none host=… hits=1
Verify state layout and isolation (modules 1, 3):
docker run --rm --network tf-lab -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION=us-east-1 \
  amazon/aws-cli --endpoint-url http://tf-minio:9000 s3 ls s3://tfstate --recursive | grep -E '^(.*)(dev|stage|prod)/(10|20|30)-' | awk '{print $4}'
for env in dev stage prod; do echo -n "$env: "; for l in 10-network 20-platform 30-app; do echo -n "$l=$(terraform -chdir=live/$env/$l state list | wc -l) "; done; echo; done
dev/10-network/terraform.tfstate
dev/20-platform/terraform.tfstate
dev/30-app/terraform.tfstate
prod/10-network/terraform.tfstate
prod/20-platform/terraform.tfstate
prod/30-app/terraform.tfstate
stage/10-network/terraform.tfstate
stage/20-platform/terraform.tfstate
stage/30-app/terraform.tfstate
dev: 10-network=1 20-platform=3 30-app=4
stage: 10-network=1 20-platform=3 30-app=5
prod: 10-network=1 20-platform=3 30-app=6

Application layer resource count = replica count + LB + two image resources (numbers may vary slightly depending on your module implementation).

Version promotion + gates (modules 6, 8): deploy myapp:1.1 to dev first, check replacements with the plan JSON gate, then promote in order:
promote() {   # $1=env
  d=live/$1/30-app
  terraform -chdir=$d plan -input=false -var image=myapp:1.1 -out=/tmp/$1.plan >/dev/null
  echo "[$1] resources to be replaced:"
  terraform -chdir=$d show -json /tmp/$1.plan | jq -r '.resource_changes[] | select(.change.actions|length==2) | "  \(.address) \(.change.actions|join("→"))"'
  terraform -chdir=$d show -json /tmp/$1.plan | jq -e '[.resource_changes[] | select(.type=="docker_volume" or .type=="docker_network") | select(.change.actions|index("delete"))] | length==0' >/dev/null \
    || { echo "Gate: application-layer plan contains network/volume deletion, rejected!"; return 1; }
  terraform -chdir=$d apply -input=false /tmp/$1.plan | tail -1
}
promote dev && curl -s localhost:8081/
# After observing for a while:
promote stage && promote prod
[dev] resources to be replaced:
  module.app.docker_container.app[0] delete→create
Apply complete! Resources: 2 added, 0 changed, 1 destroyed.
myapp v1.1 env=dev color=none host=… hits=43

The application container name in the web-service module is fixed and has no cbd, so it is “delete then create” (delete→create). Thinking question: apply module 6's “unique name + cbd + drain” to the web-service module to make promotion zero-downtime — this is a bonus item for this lab. When making the version permanent, put image into each environment's terraform.tfvars and submit a PR.

Review and risk register (module 8): run module 8's “architecture health check” script, check items in the interactive review, then write docs/adr/0001-risk-register.md, which must include at least four items: the scope of remote_state reads, prod not being in a separate account (local limitation), a gap during web-service replacement, and a single point of failure in state storage (a single MinIO), along with mitigation measures. git add -A && git commit -m "myapp-infra: 3 envs x 3 layers".
Cleanup (reverse order: application → platform → network):
for env in prod stage dev; do
  for layer in 30-app 20-platform 10-network; do
    terraform -chdir=live/$env/$layer destroy -auto-approve -input=false | tail -1
  done
done

If the redis module sets prevent_destroy = true, platform-layer destruction will be blocked — this is expected; temporarily delete that line (or comment it out) before running, and record in the ADR “who removed the protection and when”. Reverse-order destruction matters: deleting the network first will fail because containers are still using it. Finally, optionally: docker rm -f tf-minio && docker volume rm tf-minio-data (lesson 7 still uses MinIO, so keeping it is recommended).

Acceptance checklist

Open-ended self-test (answer on your own first, then expand the reference answer)

1. When is a CLI workspace appropriate? When is it not?

Appropriate: temporary copies of the same configuration (PR previews, feature branch testing) with the same credentials and access control. Not appropriate: long-lived environments that need different accounts/credentials/approvals (dev/prod), because workspaces share backend configuration and credentials, and selecting the wrong workspace changes the wrong environment.

2. Why should a module receive network_id instead of looking up the network itself with a data source?

Dependency injection makes dependencies explicit, testable, and replaceable; the caller decides whether to create new or reuse. Looking up by name inside the module hides an implicit convention inside the module; when names change or collide, it silently picks the wrong one, and it also prevents the module from being used in the scenario where the network is created in the same apply.

3. terraform_remote_state 's permissions problem? Alternatives?

It requires reading the other side's entire state snapshot, which may contain secrets (sensitive only masks them in output). Alternatives: the producer explicitly writes the values to be shared into SSM Parameter Store / Azure App Configuration (or HCP Terraform's tfe_outputs), and consumers are authorized to read only those parameters; or query with data sources by tag.

4. How do you “iterate over regions” for deployment in Terraform?

Terraform's provider blocks do not support for_each (OpenTofu supports it from 1.9). Approach: explicitly write a provider alias + module call for each region, or use one directory/state per region (recommended, for a region-level blast radius); from AWS provider 6.0, most resources support a top-level region parameter, so you can use for_each over regions at the resource level.

5. Why do write-only arguments need *_wo_version?

Write-only values are not stored in the plan/state, so Terraform cannot compare old and new values or detect changes; the version number is a regular argument stored in state, and incrementing it triggers the provider to write again.

6. How would you change the web-service module's release to zero downtime?

Add a suffix that changes with the image to the application container name (image ID hash), and set create_before_destroy, keep wait = true health wait, and drain before destroy (the provisioner waits for the DNS cache to expire during destroy, or removes it on the LB side); nginx uses a variable form of proxy_pass with a short resolver validity period. To go further, the module can offer a blue-green mode (two colors + an active_color switch).

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified date: 2026-11-15)
TopicVerified findingSource (accessed 2026-11-15)
Terraform CLILatest v1.17.2 (2026-11-11); 1.17.0 (2026-10-21): provider requirements can use variables/locals,-minimal-refresh, Terraform Policy GA, test mock_provider supports ephemeralGitHub releases / CHANGELOG
Terraform 1.14.0Released 2025-11-19: list resource (*.tfquery.hcl),terraform query,action blocks, GenerateResourceConfiguration RPC,validate -queryv1.14 CHANGELOG
Terraform 1.15.02026-04-29: variables/outputs deprecated attributes, module source/version can use variables and locals, output type constraints,convert functions; provider for_each not providedv1.15 CHANGELOG
Terraform 1.16.02026-08-26: inside modules import blocks,terraform_data 's store blocks, action trigger on_failurev1.16 CHANGELOG
terraform queryoptions -generate-config-out (file must not exist),-json,-var,-var-file,-policiesterraform query
provider blocksupports alias; not listed in the docs for_each/count; for multiple configurations in submodules, use configuration_aliasesprovider block
OpenTofuprovider for_each (only used together with alias, since 1.9); client-side state encryption (since 1.7); current version 1.13.9OpenTofu provider configuration
ephemeral / write-onlyephemeral block (1.10) allowed reference contexts; write-only arguments require 1.11+, used with *_wo_version; example resources aws_db_instance, aws_secretsmanager_secret_version, azurerm_key_vault_secret, azurerm_mysql_flexible_serverephemeral · write-only
S3 backenduse_lockfile (default false); DynamoDB locking is deprecated; endpoints.s3,use_path_style,skip_*; S3-compatible storage is best effort; remote_state only returns root module outputsS3 backend · remote_state
hashicorp/aws6.73.0 (2026-11-11); from 6.0, most resources support a top-level region; 280 list resources (such as aws_instance, some in beta); ephemeral: secretsmanager_secret_version, secretsmanager_random_password, ssm_parameter, etc.Enhanced Region Support · registry API
hashicorp/azurerm5.14.0 (2026-11-13); from 5.0, resource_provider_registrations default none, removed skip_provider_registration; value_wo/administrator_password_wo; ephemeral key_vault_secret/certificate; many list resourcesazurerm 5.0 Upgrade Guide
kreuzwerker/docker4.7.0 (2026-11-11); docker_container supports networks_advanced.aliases,healthcheck,wait/wait_timeout,upload; import ID is the full container/network ID; no list resources, no write-only argumentsregistry docs
hashicorp/random, localrandom 3.9.1 (ephemeral random_password); local 2.9.1 (ephemeral local_command)registry API
TerragruntLatest v1.2.2 (2026-11-11); terragrunt run --all replaces run-all; dependency + mock_outputsreleases · Quick Start
MinIOThe official community edition stopped publishing Docker images from 2025-10, and the repository was archived in 2026; this lesson uses the community fork pgsty/minio:RELEASE.2026-08-04T00-00-00Z (verified on Docker Hub)Docker Hub API; community reports

Video verification notes

The following videos were verified for title and channel via the YouTube oEmbed endpoint (2026-11-15): Anton Putra “How To Structure Terraform Project (3 Levels)” (nMVXs8VnrF4); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); freeCodeCamp.org “Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners” (V53AHWun17s), “Terraform Course - Automate your AWS cloud infrastructure” (SLB_c_ayRMo); KodeKloud “Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide!” (YcJ9IeukJL8); HashiCorp “Introduction to HashiCorp Terraform with Armon Dadgar” (h970ZBgKINg); TechWorld with Nana “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE). oEmbed does not return durations or publish dates, so the cards omit durations. No verified dedicated videos were found for ephemeral/write-only, create_before_destroy, import blocks/terraform query, or multi-account assume_role, so storyboard scripts are provided instead. All videos are in English and were recorded before Terraform 1.17; for new features, follow this lesson and the official docs.

Audio narration notes

The “Audio” 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. This courseware's generation environment cannot call a TTS service, so no MP3 is embedded; when offline audio is needed, the narration script can be given to a TTS service to generate it.

Known limitations

  • Lab commands were not actually executed in the generation environment; IDs, hashes, IPs, times, and counts in the “expected output” are example values, and error message wording may vary slightly across versions.
  • Local labs use Docker networks/containers to simulate cloud VNets/VPCs, databases, and applications; docker-in-docker simulates a second region; files + local_command simulate a key vault — the mechanisms are equivalent, but real IAM, quotas, and network latency are not involved.
  • The MinIO fork image's support for S3 conditional writes (use_lockfile) depends on the actual version; if locking is unavailable, ensure that only one person operates during the lab.
  • For details such as Front Door weights/priorities, Container Apps traffic blocks, RDS blue_green_update, and Azure Landing Zones module names, refer to the corresponding official docs; this lesson only provides structural illustrations.
  • -generate-config-out Generated docker_container configurations may contain attributes that need to be deleted manually; whether the generation feature still shows an “experimental” notice depends on the version used.
  • The time slices, RPN scores, and request counts in the animations are illustrative values used to explain the mechanism.