Terraform Lesson 2: From “it runs” to “production-ready”

Refactor the local myapp stack from Lesson 1 (kreuzwerker/docker) into a reusable module, connect a remote state and locking, add tests, validations and scans, and finish with a production-readiness review
Terraform v1.17.2kreuzwerker/docker 4.7.0tflint v0.66.0Trivy v0.76.2 · Checkov 3.4.5Checked against official docs · 2026-11
Overall learning goals
  • Design modules with clear input / output interfaces sub-modules, and reference modules from local paths, Git and the Terraform Registry, and pin their versions; know that module versions are not recorded in .terraform.lock.hcl.
  • Migrate local state to S3 backend (simulated with a local S3-compatible container), using -backend-config for partial configuration, and understand S3 native locking use_lockfile how it is acquired and released,force-unlock its risks, and how to isolate state by environment / component, and the pitfalls of workspaces.
  • Understand the difference between count and for_each ’s instance addresses differences, and use the moved block to safely migrate count to for_each, and use the dynamic block to generate nested blocks.
  • Use the moved / import / removed block to refactor code only, without touching infrastructure, and use -generate-config-out to generate import configuration, and explain how they differ from terraform state mv/rm,terraform import differences.
  • Use validation,precondition,postcondition,check to catch errors at different stages; use terraform test the run block,command = plan,mock_provider,override_* to write unit and integration tests.
  • Set up fmt → validate → tflint → Trivy/Checkov → test local and CI quality gates (pre-commit), and complete the checklist version constraints, the upgrade process and the production-readiness review.

1-hour time plan

#TimeModuleCore contentAnimation / interactiveLab (local Docker + myapp stack)
0Before classBridge and warm-upCheck the Lesson 1 myapp stack, versions and state; if missing, rebuild in 3 minProduction-readiness self-check (10 items)terraform plan No changes
100–08Module design and reuseRoot module / child modules, variables and outputs as interfaces, module sources, Registry modules, version pinning, module composition principlesModule call tree: inputs → resources → outputs, and how the address prefix is applied module. prefixExtract modules/stack, add a second instance: staging
208–15Remote state, locking and isolationbackend configuration, partial configuration -backend-config,-migrate-state, S3 use_lockfile,force-unlock, split by environment / component, workspaceCore animation: two operators compete for the state lock (conditional write .tflock → 412 → release / stale lock)S3-compatible container + state migration + concurrent lock demo
315–22count, for_each and dynamicinstance addresses [0] vs ["key"], cascading rebuild when deleting a middle element,for_each ’s known-value requirements,dynamiccount / for_each address comparison simulator (delete one element and see the plan)app multi-instance: migrating count → for_each
422–30Refactoring: moved, import, removedDeclarative refactoring blocks vs state mv/rm,import blocks + -generate-config-out,removed + destroy = falseCore animation: how the moved block maps old addresses in state to new addresses (avoiding destroy and recreate)Import manually created containers, remove from state
530–37Validation: validation, pre/postcondition, checkExecution timing and failure behavior of the four kinds of checks (error vs warning), cross-variable validation (1.9+)When each check fires on the plan/apply timelineAdd port / image validation and health checks to the module check
637–45terraform test and mock.tftest.hcl,run,command = plan/apply,expect_failures,mock_provider,override_resourceTest runner: run block order, shared state, mock-generated values, cleanupModule unit tests (mock) + integration tests (real Docker)
745–52Static checks and security scanningfmt,validate, tflint (ruleset), Trivy config, Checkov, pre-commit, CI gatesQuality-gate pipeline: which gate catches which defectOne-command pre-commit check; scan a deliberately insecure example
852–60Version constraints, upgrades and production-readiness reviewrequired_version, provider constraints and ~>, multi-platform hashes in the lock file, upgrade process, 1.17 new features, review checklist and scriptVersion constraint calculator + troubleshooting decision treeUpgrade drill + run the review script
—After classCheat sheet · Capstone labProduction-readiness refactor: modularization + remote state + tests + scanningFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / blocksLab
Design module interfaces and reuse them✓·✓·✓✓··module,variable,outputmodules/stack
Reference and pin third-party module versions✓······✓source,version,?ref=Registry module example
Remote state migration and locking·✓·····✓init -migrate-state,force-unlockS3-compatible backend
Isolate state by environment / component✓✓·····✓-backend-config,workspacedev / staging key
Multi-instance resources and stable addresses··✓✓····count,for_each,dynamiccount → for_each
Lossless refactoring (no destroy and recreate)✓·✓✓····moved,state mvModularization migration
Bring existing resources under management / stop managing them···✓····import,removed,-generate-config-outImport manually created containers
Input and runtime contract validation✓···✓✓··validation,precondition,checkPort / health check
Automated tests (mock / integration)····✓✓✓·terraform test,mock_providertests/*.tftest.hcl
Static checks and security scanning······✓✓tflint,trivy config,checkovpre-commit
Version management and upgrades✓······✓init -upgrade,providers lockUpgrade drill

Out of scope for this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn
Azure Storage backend (azurerm), Entra ID authentication, real cloud resourcesEverything in this lesson runs on local Docker, at zero costLesson 3: Moving to a cloud platform (Azure)
Real AWS S3 backend deployment, KMS encryption, least-privilege IAMThis lesson only simulates the protocol with an S3-compatible containerLesson 4: Moving to a cloud platform (AWS)
CI/CD pipelines, OIDC, plan approval, HCP Terraform, Policy (Sentinel / OPA / Terraform Policy)Belongs to the automation-operations topic; this lesson only covers a basic local pre-commit and CI gateLesson 5: Automation operations
Multi-account / multi-subscription landing zones, Stacks, large-state splitting architectureBelongs to the architecture topicLesson 6: Architecture in practice
State corruption recovery, drift investigation, performance tuning (-parallelism,-minimal-refresh)Belongs to deep troubleshootingLesson 7; this lesson's m8 troubleshooting tree provides the entry point

How to use these course materials

10 pages per module
Theory · diagrams · animation · commands · lab · production cases · troubleshooting · quiz · audio · video. We recommend reading “Theory” and “Animation” first, then doing the “Lab” in your own ~/tf-lab/myapp directory and do the “Lab”.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (if local storage is blocked, it is cleared on refresh).
Chinese audio
The “Audio” page reads the script aloud with the browser's built-in Web Speech API (en-US); without a Chinese voice pack the script is still readable, or you can pass it to another TTS tool.
Version notes This lesson is based on Terraform v1.17.2 (2026-11-11) as the baseline; 1.16.x can also complete all labs. Version in which each feature was introduced: moved block 1.1; import block and check block 1.5; terraform test 1.6; removed block,import block's for_each, and the mock_provider / override_* in 1.7; cross-resource-type moved (requires provider support) 1.8; validation referencing other variables / objects 1.9; S3 backend's use_lockfile native locking 1.10 experimental, 1.11 GA (DynamoDB locking deprecated). Provider: kreuzwerker/docker 4.7.0 (2026-11-11). Tools: tflint v0.66.0 (adds Terraform 1.17 support), tflint-ruleset-terraform v0.17.0, Trivy v0.76.2, Checkov 3.4.5, pre-commit-terraform v1.109.5, pre-commit 4.7.0. The MinIO Community Edition repository was archived on 2026-04-25 and no longer publishes prebuilt binaries; the Docker Hub minio/minio repository was no longer accessible at the time of verification, so the m2 lab uses MinIO as the example for parameters, and also provides a directly pullable S3-compatible replacement image (RustFS 1.0.5); see m2.

Module 0 · Bridge and warm-up (complete before class)

Confirm that the Lesson 1 myapp stack (network + redis + app) is still managed by Terraform and that plan is clean; if it has been destroyed, rebuild it from the baseline code below in 3 minutes
Before class ≈ 8 minTerraform 1.17.2 · Docker Engine 29
Prerequisites
  • CompletedLesson 1: directory ~/tf-lab/myapp contains one stack managed with kreuzwerker/docker a local stack: network myapp-net, container myapp-redis (redis:7-alpine), container myapp (from the Docker lesson's myapp:1.0, Flask + gunicorn, listening on 5000,/healthz), host port 8080.
  • Workstation: Ubuntu 24.04 LTS (Azure VM or local machine), Docker Engine 29.x, current user in the docker group; Terraform 1.17.x.
  • The additional tools needed for this lesson (tflint, Trivy, Checkov, pre-commit) are installed in the m7 lab, so no need to prepare them before class.

Step 1: Check versions and the existing stack

terraform version
docker version --format 'Docker Engine {{.Server.Version}}'
cd ~/tf-lab/myapp
terraform state list
terraform plan -detailed-exitcode; echo "exit=$?"
curl -s localhost:8080/healthz
Terraform v1.17.2
on linux_amd64
+ provider registry.terraform.io/kreuzwerker/docker v4.7.0
Docker Engine 29.9.3
docker_container.app
docker_container.redis
docker_image.app
docker_image.redis
docker_network.app
...
No changes. Your infrastructure matches the configuration.
exit=0
ok

-detailed-exitcode: 0 = no changes, 1 = error, 2 = changes present. This is the standard CI pattern for detecting drift, which the m8 review script uses. /healthz returns content that depends on the implementation you wrote in the Docker lesson; a 200 response is enough.

Step 2 (only if the stack was destroyed or Lesson 1 used different names): rebuild with the baseline code

All addresses in this lesson moved use the resource names below (docker_network.app,docker_image.redis,docker_container.redis,docker_image.app,docker_container.app). If you used different names in Lesson 1, the simplest approach is to terraform destroy and then rebuild per this list; or in m4 follow along and change moved 's from to your addresses.

terraform {
  required_version = ">= 1.16.0"
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.7"
    }
  }
}

provider "docker" {}   # default connects to unix:///var/run/docker.sock
variable "app_image" {
  type    = string
  default = "myapp:1.0"
}

variable "external_port" {
  type    = number
  default = 8080
}

resource "docker_network" "app" {
  name = "myapp-net"
}

resource "docker_image" "redis" {
  name         = "redis:7-alpine"
  keep_locally = true
}

resource "docker_container" "redis" {
  name    = "myapp-redis"
  image   = docker_image.redis.image_id
  restart = "unless-stopped"
  networks_advanced {
    name    = docker_network.app.name
    aliases = ["redis"]
  }
}

resource "docker_image" "app" {
  name         = var.app_image
  keep_locally = true          # locally built image, not deleted on destroy
}

resource "docker_container" "app" {
  name    = "myapp"
  image   = docker_image.app.image_id
  restart = "unless-stopped"
  env     = ["REDIS_HOST=redis"]
  ports {
    internal = 5000
    external = var.external_port
  }
  networks_advanced {
    name = docker_network.app.name
  }
}

output "url" {
  value = "http://localhost:${var.external_port}"
}

If this machine doesn't have myapp:1.0, go back to the myapp directory from Docker Hour 1 and run docker build -t myapp:1.0 .. As a temporary alternative, you can also set app_image to nginx:alpine and change internal to 80 and continue this lesson (the health-check path changes to /).

mkdir -p ~/tf-lab/myapp && cd ~/tf-lab/myapp
# After writing the versions.tf and main.tf above:
terraform init
terraform apply -auto-approve
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/healthz
git init -q 2>/dev/null; printf '.terraform/\n*.tfstate\n*.tfstate.*\n*.tfplan\n' > .gitignore
git add -A && git commit -qm "lesson1 baseline" && git log --oneline | head -1
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

Outputs:

url = "http://localhost:8080"
200
3f1c2ab lesson1 baseline
Why use git This lesson restructures the code several times (modularization, for_each, moved blocks). Commit after each step, so when something goes wrong git diff you can immediately see “which code change caused plan to destroy resources”. Note .terraform.lock.hcl to commit,*.tfstate do not commit.

Warm-up: answer from memory (30 seconds)

What does a “resource address” stored in the state file look like? How does it relate to the code?

For example docker_container.app,docker_container.app[0],module.stack.docker_container.app["web1"]. The address is determined by the location in the code (module path + resource type + name + instance key); Terraform uses the address to map resources in the code to real object IDs in state. Renaming = address change = by default treated as “delete old, create new” — this is the core problem of m3 and m4 in this lesson.

What happens if two people run apply against the same local state on their own computers at the same time?

Local state lives on one machine, so each copy quickly diverges; even on a shared drive, the local backend's lock only works for processes on the same machine. Team collaboration must use a remote backend + locking (m2).

terraform validate What problems can it catch, and what can't it catch?

It can catch syntax errors, references to nonexistent variables / resources, type mismatches and missing required arguments; it cannot catch “port already in use”, “image does not exist”, “insecure configuration” or “non-compliant naming” — these are handled by precondition/check (m5), test (m6) and tflint/Trivy/Checkov (m7) respectively.

Production-readiness self-check (10 items)

Tick the items your Terraform code already meets currently meets (saved in this browser). Come back and tick them again after finishing this lesson and the capstone lab.

Environment self-check list

Module 1 · Module design and reuse

00:00 – 08:00 · A module is “a directory of .tf files”; variables are its parameters, outputs are its return values, and the address prefix module.NAME is its namespace in state
8 minGA (since Terraform 0.x)★★★★★
Learning goals
  • Distinguish root module (the directory where you run terraform commands) and child module (called by a module block directory), and explain a child module's variable scope, provider inheritance and address prefix.
  • Design a minimal, stable interface for the myapp stack: required inputs, optional inputs (with default values and optional()), outputs; know what should not be exposed.
  • Use three kinds of sources: local paths, the Terraform Registry and Git (?ref=), and pin versions correctly; know that module versions are recorded in .terraform/modules/modules.json, not in .terraform.lock.hcl.
Prerequisites: Lesson 1's variable / output / local, and resource addresses. Importance:★★★★★ (all later cloud courses organize code with modules)

What: what a module is

In Terraform,every directory containing .tf files is a module. The directory where you run terraform plan/apply is called the root module; in code, a directory called with module "name" { source = … } is called a child module. A child module can call further child modules, forming a module tree, and the whole tree shares one state file, one plan and one dependency graph.

  • Inputs: the child module's variable blocks; the caller sets values by name in the module block. A child module cannot see the caller's variables, locals and resources; it only sees the values passed in — this is the “interface”.
  • Outputs: the child module's output blocks; the caller reads them via module.NAME.OUTPUT . A child module's internal resource attributes are not visible externally unless explicitly output.
  • Address: resources in a child module carry a prefix in their state address, for example module.stack.docker_container.app; for multi-instance modules it is module.stack["dev"].docker_container.app.
  • provider: by default a child module inherits the root module's default provider configuration (same local name); when multiple configurations are needed (e.g. two Docker hosts, two Azure subscriptions), use providers = { docker = docker.remote } to pass them explicitly; inside the child module, only write required_providers (add configuration_aliases if needed),and do not write a provider block.

Why: why modularize

  • Reuse: the same myapp stack deploys to dev / staging / prod with only different parameters. Copy-pasting three copies of the code will guarantee they diverge within three months.
  • Encapsulation and constraints: module authors can hard-code “required security settings” inside the module, and callers can only choose from allowed parameters (for example, only port and image may be passed, and running as privileged is not allowed).
  • Units for review and testing: modules have clear inputs and outputs, so you can write terraform test (m6) for them alone, and release and upgrade them separately.

How: how modules are loaded and executed

  1. terraform init: the module installer reads the module of each source/version. Local paths (starting with ./ or ../ ), are not copied, but referenced directly; remote sources (Registry, Git, HTTP, S3, GCS) are downloaded to .terraform/modules/<key>/ and the result is written to .terraform/modules/modules.json. Changing source or version must be followed by re-running init (or terraform get).
  2. Load configuration: Terraform core recursively parses the module tree and checks each module's required_providers, and merges the global provider requirements (this is why child modules must declare source = "kreuzwerker/docker", otherwise it is treated as hashicorp/docker).
  3. Build the dependency graph: each module's variables, locals and outputs are nodes in the graph. A module is not a single node— in the root module, module.stack.app_url references depend only on the resources that produce that output, so resources from different modules can be created in parallel.
  4. plan/apply: same as ordinary resources, except that the address carries a module prefix; each resource instance in state records "module": "module.stack".

Module source (source) overview

SourceSyntaxHow to pin the versionUse case
Local pathsource = "./modules/stack"same git commit as the caller (no version)private modules within a single repo
Terraform Registrysource = "terraform-aws-modules/vpc/aws"version = "~> 6.7" (only Registry sources support version argument)Public / private Registry (HCP Terraform)
Gitsource = "git::https://github.com/org/tf-modules.git//stack?ref=v1.4.0"?ref= Tag or commit SHA (SHA is the strictest)Internal enterprise module repository
GitHub shorthandsource = "github.com/org/tf-modules//stack?ref=v1.4.0"Same as aboveSame as above
HTTP / S3 / GCS archivesource = "s3::https://s3.amazonaws.com/bucket/stack-1.4.0.zip"Version in file nameOffline / artifact repository distribution

Double slash // means “a subdirectory within the repository”. ?ref= must come after the subdirectory. For private Git repos, use SSH (git::ssh://git@github.com/org/repo.git), or a credential helper,do not put tokens into source.

When: when to extract modules and how big

  • the same group of resources appears at least twice, or when it represents a “product” with a clear boundary (an application stack, a network, a database). Do not wrap a single resource in a thin module (for example, one that only wraps docker_network), which only adds a layer of indirection.
  • Keep the module hierarchy flat: the root module composes several “component modules”, and component modules should avoid further nesting (HashiCorp's recommended module composition). Dependencies connect via outputs → inputs in the root module, rather than using data sources inside a module to “find” another module's resources.
  • Interface design: keep required inputs to a minimum; give optional inputs safe defaults; use optional(type, default) for object-type inputs; output “what callers actually need” (URL, name, ID), not the entire resource object.

Comparison with similar technologies

Terraform moduleHelm Chart (K8s lesson)Ansible RoleBicep module
Parametersvariable (strongly typed + validation)values.yaml (optional schema)defaults / varsparam (strongly typed)
Return valuesoutputNone (relies on NOTES / naming conventions)registered variables / factsoutput
Version distributionRegistry / Git refChart repository / OCIGalaxy / GitBicep Registry (ACR)
Stateshares one state with the callerone Secret per releaseStatelessAzure deployment records
Common misconceptions① “.terraform.lock.hcl will lock module versions” — it does not; the lock file only records provider versions and hashes; module versions are pinned by version a constraint or ?ref= a pin,~> 6.7 such a constraint, when init -upgrade running init -upgrade, can still pick up new minor versions. ② “Writing provider blocks inside child modules is more convenient” — modules that contain provider blocks cannot use count/for_each/depends_on, and deleting the module call will destroy the provider configuration along with it, so its resources cannot be destroyed. ③ “Moving code into a module lets Terraform recognize the same resources automatically” — no: the address has changed, so the default plan is destroy-then-create; you must use a moved block (used in this module's lab first; explained in detail in m4).

Architecture diagram: myapp's module tree and interfaces

Root module ~/tf-lab/myapp versions.tf · provider "docker" {} backend "s3" {} (m2) module "stack" source = "./modules/stack" name_prefix = "myapp" external_port = 8080 module "stack_staging" Same source name_prefix = "myapp-stg" external_port = 8090 Inputs Child module modules/stack variables.tf: name_prefix · app_image · external_port · redis_image · env docker_network.this docker_image.redis docker_container.redis docker_image.app docker_container.app (multi-instance with for_each from m3) versions.tf: required_providers { docker = { source = "kreuzwerker/docker" } } No provider block → inherits the root module's default docker provider outputs.tf: app_urls · network_name · container_names Outputs Caller reads module.stack .app_urls Internal attributes not directly accessible
Figure 1-1: the same child module is called twice, producing two independent sets of resources; the interface is only variables and outputs

Flowchart: terraform init what happens for each source

module blocksource / version Local path ./modules/stackNo download; reference the directory directly Registry ns/name/providerGET /v1/modules/…/versions git::…?ref=v1.4.0git clone + checkout ref Select the latest version that satisfies the constraintDownload to .terraform/modules/ modules.jsonKey / SourceVersion / Dir(not recorded in the lock file)
Figure 1-2: local path modules are also recorded in modules.json (Dir points to the source directory); remote modules are downloaded and cached

Step-by-step animation: how modules are “expanded” during a plan

Select the module call to observe, then play step by step. Under each step, the terminal shows the real files or logs that Terraform reads and writes at that stage (TF_LOG=debug ), you can see similar information.

Dependency graph node
Address in state

Core commands and arguments

CommandPurposeKey arguments / notes
terraform initInstall modules and providers, initialize the backend-upgrade Upgrade modules and providers within constraints; must be re-run after changing source/version
terraform getDownload / update modules only-update Check remote modules for new versions
terraform modules -jsonList all installed modules in the working directory and whether configuration still references them (new in 1.10)JSON output makes it easy to audit module sources in CI
terraform state list module.stackList resource instances in a moduleThe filter argument is an address prefix
terraform plan -target=module.stack_stagingPlan only one module (emergency use)Do not rely on it day to day -target, as it skips drift detection for other resources
terraform output -jsonView root module outputsChild module outputs must be re-exposed with output in the root module to be visible
terraform consoleInteractive evaluationTrial evaluation module.stack.app_urls, functions, type conversions
cd ~/tf-lab/myapp
terraform init            # must run after adding a module block
cat .terraform/modules/modules.json | python3 -m json.tool
terraform modules -json | python3 -m json.tool | head -20
Initializing modules...
- stack in modules/stack
- stack_staging in modules/stack
Initializing provider plugins...
- Reusing previous version of kreuzwerker/docker from the dependency lock file
...
{
    "Modules": [
        { "Key": "", "Source": "", "Dir": "." },
        { "Key": "stack", "Source": "./modules/stack", "Dir": "modules/stack" },
        { "Key": "stack_staging", "Source": "./modules/stack", "Dir": "modules/stack" }
    ]
}

How to verify:terraform modules -json fields depend on your version; the key is seeing both calls point to ./modules/stack. Common errors: If you forget to re-run init, plan reports Module not installed. Production use: Parse in CI modules.json or terraform modules -json, and reject modules from unapproved sources (non-company Git, unpinned ref).

Registry modules: three levels of version pinning strictness

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "6.7.3"        # strictest: exact version (released 2026-09-18, verified 2026-11-15)
  # version = "~> 6.7"     # allows 6.7.x and later 6.x (>= 6.7, < 7.0)
  # version = "~> 6.7.0"   # allows only 6.7.x patches
  name = "lab"
  cidr = "10.0.0.0/16"
}

module "stack_from_git" {
  source = "git::https://github.com/example-org/tf-modules.git//stack?ref=v1.4.0"
  # strictest: ?ref=0f3c9a1d... (full commit SHA; tags can be moved, SHAs cannot)
  name_prefix = "demo"
}

This is only a syntax demonstration; this lesson will not apply this AWS module. For third-party modules in production, we recommend an exact version or ~> x.y.0; read the CHANGELOG when upgrading and plan in a non-production environment first; or mirror the module into the company's internal Registry / Git and reference it from there.

Trial-evaluate module outputs in the console

echo 'module.stack.app_urls' | terraform console
echo 'module.stack_staging.container_names' | terraform console
{
  "web1" = "http://localhost:8080"
}
[
  "myapp-stg",
  "myapp-stg-redis",
]

Lab 1: extract the myapp stack into a module with zero-destroy migration (about 8 min)

Create the child module directory and interface
cd ~/tf-lab/myapp
mkdir -p modules/stack
terraform {
  required_version = ">= 1.16.0"
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = ">= 4.0, < 5.0"   # wide constraint in the module; the exact version is set by the root module's lock file
    }
  }
}
variable "name_prefix" {
  description = "Prefix for all Docker object names, e.g. myapp, myapp-stg"
  type        = string
}

variable "app_image" {
  description = "Application image (including tag)"
  type        = string
  default     = "myapp:1.0"
}

variable "redis_image" {
  description = "Redis image (including tag)"
  type        = string
  default     = "redis:7-alpine"
}

variable "external_port" {
  description = "Host port, mapped to container port 5000"
  type        = number
  default     = 8080
}

variable "env" {
  description = "Extra application environment variables"
  type        = map(string)
  default     = {}
}
locals {
  app_env = merge({ REDIS_HOST = "redis" }, var.env)
}

resource "docker_network" "this" {
  name = "${var.name_prefix}-net"
}

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

resource "docker_container" "redis" {
  name    = "${var.name_prefix}-redis"
  image   = docker_image.redis.image_id
  restart = "unless-stopped"
  networks_advanced {
    name    = docker_network.this.name
    aliases = ["redis"]
  }
}

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

resource "docker_container" "app" {
  name    = var.name_prefix
  image   = docker_image.app.image_id
  restart = "unless-stopped"
  env     = [for k, v in local.app_env : "${k}=${v}"]
  ports {
    internal = 5000
    external = var.external_port
  }
  networks_advanced {
    name = docker_network.this.name
  }
}
output "network_name" {
  value = docker_network.this.name
}

output "app_url" {
  value = "http://localhost:${var.external_port}"
}

output "container_names" {
  value = [docker_container.app.name, docker_container.redis.name]
}

Note env The original form is ["REDIS_HOST=redis"], here we use for an expression to generate the same list, so the attributes match exactly after migration (otherwise container replacement is triggered).

Rewrite the root module: delete the original 5 resources and replace them with a module call + moved block
variable "app_image" {
  type    = string
  default = "myapp:1.0"
}

variable "external_port" {
  type    = number
  default = 8080
}

module "stack" {
  source        = "./modules/stack"
  name_prefix   = "myapp"
  app_image     = var.app_image
  external_port = var.external_port
}

output "url" {
  value = module.stack.app_url
}
moved {
  from = docker_network.app
  to   = module.stack.docker_network.this
}
moved {
  from = docker_image.redis
  to   = module.stack.docker_image.redis
}
moved {
  from = docker_container.redis
  to   = module.stack.docker_container.redis
}
moved {
  from = docker_image.app
  to   = module.stack.docker_image.app
}
moved {
  from = docker_container.app
  to   = module.stack.docker_container.app
}
First, deliberately skip moved and see what happens
terraform init
mv moved.tf moved.tf.off
terraform plan | tail -5
mv moved.tf.off moved.tf
  # module.stack.docker_network.this will be created
...
Plan: 5 to add, 0 to change, 5 to destroy.

“5 to add, 5 to destroy”: Terraform sees the resources at the old addresses disappear from the code (to be destroyed) and the resources at the new addresses as new (to be created). For containers that means downtime; for databases and storage accounts it means data loss. Never apply this.

Enable moved, plan again, confirm 0 destroys, then apply
terraform plan
terraform apply -auto-approve
terraform state list
  # docker_container.app has moved to module.stack.docker_container.app
    resource "docker_container" "app" {
        id    = "4c1f9e…"
        name  = "myapp"
        # (31 unchanged attributes hidden)
    }
  # docker_network.app has moved to module.stack.docker_network.this
...
Plan: 0 to add, 0 to change, 0 to destroy.
...
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
module.stack.docker_container.app
module.stack.docker_container.redis
module.stack.docker_image.app
module.stack.docker_image.redis
module.stack.docker_network.this

apply only rewrites the addresses in state; the Docker container IDs stay the same (docker ps --format '{{.ID}} {{.Names}}' comparing before and after proves it).

Reuse: add a staging instance
module "stack_staging" {
  source        = "./modules/stack"
  name_prefix   = "myapp-stg"
  external_port = 8090
  env           = { APP_ENV = "staging" }
}

output "staging_url" {
  value = module.stack_staging.app_url
}
terraform init && terraform apply -auto-approve
docker ps --format 'table {{.Names}}\t{{.Ports}}' | grep myapp
curl -s -o /dev/null -w "%{http_code}\n" localhost:8090/healthz
git add -A && git commit -qm "m1: extract modules/stack, add staging"
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
NAMES             PORTS
myapp-stg         0.0.0.0:8090->5000/tcp
myapp-stg-redis   6379/tcp
myapp             0.0.0.0:8080->5000/tcp
myapp-redis       6379/tcp
200

The two docker_image resources pointing to the same local image is safe: the image resource only “ensures the image exists”,keep_locally = true so destroying staging will not delete the image prod is also using.

Cleanup (optional): staging will be used in m2 to demonstrate state isolation, so you can keep it for now. To delete it, remove from main.tf module "stack_staging" and staging_url then run terraform apply.

Case 1: code for three environments quietly “diverges”

Problem: A team copied the dev directory to create staging and prod; half a year later someone added a log volume to prod on the fly but not to dev; an upgrade passed in dev but failed in prod. Approach: Extract modules/app-stack, the three environment directories are left with only about 20 lines of calling code and terraform.tfvars; environment differences must appear explicitly in parameters. Configuration:live/{dev,staging,prod}/main.tf Reference ../../modules/app-stack, with one independent backend key per directory (m2). Limitation: A local-path module means all three environments always use the same module code; to let prod upgrade later, switch to a Git ref or a Registry version.

Case 2: the platform team publishes a “golden module”

Problem: Each business team writes its own storage accounts, and someone forgot to disable public network access. Approach: The platform team publishes, in an internal Git repository, storage-account a module that hard-codes TLS 1.2, blocks public blobs and uses private endpoints, exposing only name, SKU and network rules; each release gets a semantic version tag. Configuration:source = "git::ssh://git@github.com/acme/tf-modules.git//storage-account?ref=v2.3.1", CI uses Checkov (m7) to scan the caller's code. Limitation: The more “all-purpose” a module is, the harder it is to maintain; use optional() object parameters to control interface bloat; breaking changes bump the major version and the CHANGELOG documents migration steps (including moved blocks).

Case 3: a Registry module's “automatic” upgrade causes changes

Problem: Using version = ">= 5.0" a community VPC module, and someone running init -upgrade, on a new machine got a new major version, and plan showed dozens of resource replacements. Approach: Standardize on ~> x.y.0 or an exact version, with Renovate/Dependabot opening upgrade PRs that include the plan output. Limitation: Module versions are not in the lock file, so they can only be controlled through constraints and code review.

Common errors and fixes

Error: Module not installed ... This module is not yet installed. Run "terraform init" to install all modules required by this configuration.

Cause: A module block was added or source/version, but initialization was not re-run.

terraform init        # or update modules only: terraform get

Prevention: The first step in CI is always terraform init (you can add -backend=false for a pure static check).

Error: Failed to query available provider packages ... provider registry.terraform.io/hashicorp/docker: provider registry registry.terraform.io does not have a provider named registry.terraform.io/hashicorp/docker

Cause: The child module does not declare required_providers, so Terraform uses the resource prefix docker_ to infer the default namespace hashicorp/docker (which does not exist).

terraform providers     # see the provider source each module requires

Fix: In each module that uses that provider, declare docker = { source = "kreuzwerker/docker" }.

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

Cause: The module block passes a variable the child module does not define (a typo, or the child module's interface was renamed).

Fix: Check against the child module's variables.tf; when renaming an interface, the module author should keep the old variable for a while and mark it deprecated in its description.

Error: Unsupported attribute ... This object does not have an attribute named "container_id".

Cause: The caller reads module.stack.container_id, but the child module has no such output. Its internal resources are not visible externally.

Fix: Add an output in the child module outputs.tf or use an existing output instead.

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

Cause: A provider block was written provider "docker" { … } inside the child module.

Fix: Move the provider block to the root module; the child module keeps only required_providers; when multiple configurations are needed, use configuration_aliases + the caller's providers = { … }.

Command-line tasks
1. List the resources in state that belong to module.stack_staging all resources, and show the attributes of the app container.
terraform state list module.stack_staging
terraform state show module.stack_staging.docker_container.app
2. Update only the remote module to the newest version allowed by the constraint, without upgrading the provider.
terraform get -update
# Compare: terraform init -upgrade upgrades both modules and providers (and rewrites .terraform.lock.hcl)
Scenario analysis
A colleague moved a group of Azure resources from the root module into modules/network, and plan shows “12 to add, 12 to destroy”. He plans to apply because “the names are the same, so Azure will reuse them.” How do you respond?

Do not apply. After the address changes, Terraform first destroys the real resources at the old addresses (the VNet, subnets and NSGs would all be deleted, and the VMs / private endpoints that depend on them would be affected), and only then creates new ones — there is no “reuse”. The correct approach: write moved { from = azurerm_virtual_network.main to = module.network.azurerm_virtual_network.this }, then plan, confirm “0 to destroy”, and then apply; keep the moved blocks for at least one release cycle so other environments can migrate in sync (see m4).

Verified teaching videos

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · full course; the “Modules” and “Managing multiple environments” chapters map directly to this module and m2 (recorded before 1.17; the new syntax in this lesson takes precedence)
▶
HashiCorp Terraform Associate Certification Course - Pass the Exam! — freeCodeCamp.org
English · certification-oriented long course with a systematic explanation of module sources, Registry and version constraints

Official documentation

Video storyboard script (about 90 seconds)

This lesson's materials cannot directly generate a video or MP3; a storyboard and narration script are provided for a video tool to generate.

Shot 1 · 0–15s
Visual: three nearly identical folders dev, staging, prod, with one red line of code added to prod.
Narration: copy-pasted environments inevitably diverge. Modules let the same code be deployed multiple times with different parameters.
Shot 2 · 15–40s
Visual: a box labeled modules/stack, with two “input lines” name_prefix and external_port entering from the left and an “output line” app_url leaving to the right.
Narration: a module's interface is only its variables and outputs. Callers can neither see nor directly reference the resources inside the module.
Shot 3 · 40–65s
Visual: the addresses in the state list each gain the prefix module.stack, with a moved arrow appearing beside them.
Narration: when resources move into a module their addresses change. Without a moved block the plan destroys then recreates; with a moved block, only the addresses in state are rewritten.
Shot 4 · 65–90s
Visual: the Registry page, version 6.7.3, and a lock icon covering only the provider, not the module.
Narration: the lock file only locks providers. Module versions must be pinned with a version constraint or a Git ref; in production, use exact versions.
or score ≥ 70% on the quiz

Module 2 · Remote state, locking and isolation

08:00 – 15:00 · state is Terraform's “ledger”: keep it in shared storage, allow only one writer at a time, and keep separate books per environment and component
7 minS3 use_lockfile GA (1.11)DynamoDB locking is deprecated★★★★★
Learning goals
  • Write the partial configuration (only the code contains backend "s3" {}, and the rest goes in a *.tfbackend file, passed in with -backend-config ), and migrate local state to it safely with -migrate-state safely.
  • Explain the mechanics of use_lockfile : S3 conditional writes <key>.tflock → success means the lock is held → deleted when the operation ends; when it is occupied, the error Error acquiring the state lock; clear a stale lock with force-unlock the prerequisites for clearing.
  • Design state boundaries as “environment × component”; know what CLI workspaces are good and bad for (they are not a security boundary for environment isolation).
Prerequisites: Lesson 1 state basics (serial, lineage,terraform state list/show). Importance:★★★★★ (a prerequisite for team collaboration)

What: backend and state locking

backend determines where state lives and how it is locked. The default is local (the current directory's terraform.tfstate, and the lock is the same-directory .terraform.tfstate.lock.info, which only works for processes on this machine). Remote backends include s3,azurerm,gcs,remote/cloud (HCP Terraform),consul,pg,kubernetes,http , etc.

  • state lock: all operations that may write state (plan, apply, destroy, import, state mv/rm, refresh, etc.) acquire the lock before starting and release it when finished. The purpose of the lock is to stop two processes from computing from the same old state and overwriting each other.
  • S3 native locking use_lockfile = true (1.10 experimental,1.11 GA): uses S3's conditional write (PutObject with If-None-Match: *, returning 412 PreconditionFailed) to create a <key>.tflock object next to the state. The old dynamodb_table locking has been deprecated; official documentation states it will be removed in a future minor version; both can be enabled at the same time during migration.
  • partial configuration: a backend block cannot reference variables, locals or data sources, because it must be initialized before the configuration is loaded. So the backend block is often left as an empty backend "s3" {}, and the specific parameters are passed via -backend-config=file or -backend-config="key=value" at init time.

Why: why remote state + locking is required

  • Collaboration: everyone and CI read and write the same state; local state starts diverging the day a second person joins.
  • Security: state contains all attributes of resources, often including plaintext passwords, connection strings, private keys (even if the variable is marked sensitive, the state still stores it in plaintext). Remote storage can provide encryption, access control, auditing and versioning (rollback after accidental deletion).
  • Concurrency protection: without locking, two applies may both compute from serial 7, and the later write overwrites the earlier one, causing “resources lost from state”, and the next plan tries to create them again.

How: what the backend does during one apply (S3 + use_lockfile)

  1. Lock(): PutObject tfstate/myapp/dev/terraform.tfstate.tflock, with If-None-Match: *, whose content is lock-info JSON (ID, Operation, Who, Version, Created, Path). Returning 200 means the lock is held; returning 412 means someone else holds it, and Terraform reads the lock object's content and prints Lock Info, then -lock-timeout retries or reports an error.
  2. RefreshState(): GetObject terraform.tfstate, checks lineage and serial.
  3. plan / waiting for confirmation / apply: An interactive apply keeps holding the lock while it waits for you to type yes.. During apply, Terraform periodically persists intermediate state.
  4. PersistState(): PutObject terraform.tfstate, serial + 1.
  5. Unlock(): after reading the lock object and confirming the ID matches, DeleteObject …tflock. If the process is killed, power is lost, or the CI runner is reclaimed, this step does not run and a kill -9, leaving behind a stale lock.

Extra parameters needed for S3-compatible storage (MinIO etc.) (verified against the official S3 backend documentation)

ParameterPurposeLocal lab value
endpoints = { s3 = "…" }Custom S3 endpoint (the old parameter endpoint has been replaced by endpoints.s3 )http://127.0.0.1:9000
use_path_styleUse http://host/bucket/key path-style addressing (old name force_path_style)true
skip_credentials_validationDo not call STS to validate credentialstrue
skip_requesting_account_idDo not query the account ID via IAM/STStrue
skip_region_validationDo not validate the region name as an AWS regiontrue
skip_metadata_api_checkDo not access the EC2 instance metadata servicetrue
skip_s3_checksumDo not attach new checksum headers on upload (some S3-compatible implementations do not support them)true
use_lockfileEnable S3 native lockingtrue (requires storage that supports conditional writes)

The official documentation explicitly states that support for non-AWS S3-compatible services is best effort, and HashiCorp only tests against Amazon S3. workspace_key_prefix Default is env:, and the state for non-default workspaces is stored at env:/<workspace>/<key>.

When: how to split state (isolation strategy)

ApproachHowProsRisks / limits
Per-environment directory + separate key (recommended)live/dev,live/prod each with -backend-config=dev.s3.tfbackend; prod can use a different bucket / account / credentialssmall blast radius; permissions can be isolated (dev credentials cannot read prod state); code differences are explicitmore directories, with modules (m1) removing duplication
Split by componentnetwork, data and app belong to different root modules and keysfaster plans and smaller change impact; the network rarely changes, so it does not need to be planned with every app changecross-state dependencies require passing values (output → variable, or terraform_remote_state / data source)
CLI workspaceSame directory terraform workspace new staging, multiple states under the same backend configurationQuickly create temporary copies (feature branches, test environments)same code and same credentials; easy to apply in the wrong workspace; no permission isolation; resource names must use terraform.workspace to distinguish them, otherwise they conflict

Comparison with similar technologies

S3 backendazurerm backendHCP TerraformOpenTofu
Locking mechanism.tflock Conditional writes (DynamoDB deprecated)Blob leaseBuilt-in workspace lockTerraform-native backend; also has state encryption
EncryptionSSE-S3 / SSE-KMS (encrypt,kms_key_id)storage-service encryption + optional CMKManaged by the platformClient-side state encryption (since 1.7)
Where to learnThis module / Lesson 4Lesson 3Lesson 5—
Common misconceptions① “Using workspaces achieves environment isolation” — workspaces share the same backend configuration and credentials; HashiCorp's documentation explicitly states they are not suitable for deployment isolation that requires separate credentials and access control. ② “When you see a lock error, just -lock=false or force-unlock” — a lock error usually means someone really is operating; first confirm from the Who/Created fields in Lock Info that the other process no longer exists, then run force-unlock. ③ “Marking a variable sensitive makes state safe” — sensitive only affects CLI output; state still stores it in plaintext, so the state storage itself must be protected. ④ “You can write variables in the backend” — key = "${var.env}/terraform.tfstate"” — no; the backend block cannot use variables; use -backend-config.

Architecture diagram: remote state in the local lab

Operator A (terminal 1)terraform applyAWS_ACCESS_KEY_ID …-backend-config=dev.s3.tfbackend Operator B / CIterraform planSame bucket + key-lock-timeout=5m S3 API S3 API S3-compatible storage container (127.0.0.1:9000) bucket: tfstate (versioning enabled) myapp/dev/terraform.tfstateserial 12 · lineage 9e3c… myapp/dev/terraform.tfstate.tflockexists only while the lock is held myapp/staging/terraform.tfstateanother key = another ledger, another lock env:/scratch/myapp/dev/terraform.tfstateCLI workspace "scratch" Docker Enginemyapp / myapp-redismyapp-netstate is just the ledger;the real objects are here
Figure 2-1: each key has one state and one lock; a workspace just adds env:/name/

Sequence diagram: acquiring and releasing the lock

A: terraform applyS3 (tfstate bucket)B: terraform plan PutObject .tflock If-None-Match: * 200 OK → lock acquired GetObject terraform.tfstate (serial 12) PutObject .tflock If-None-Match: * 412 PreconditionFailed → read lock info → error / retry waiting for yes · applying resources PutObject terraform.tfstate (serial 13) DeleteObject .tflock → released retry PutObject .tflock → 200 (reads serial 13)
Figure 2-2: lock object exists = someone holds the lock; if the process exits abnormally, DeleteObject never runs and the lock is left behind

Core animation: two operators compete for the state lock

Choose a scenario and play it step by step. The left and right columns are two terminals; the middle is the object in the bucket. The terminal below shows the S3 requests Terraform actually sends and the CLI output.

Terminal A
s3://tfstate/myapp/dev/
Terminal B

Core commands and arguments

CommandPurposeKey arguments / notes
terraform init -backend-config=FILEInitialize the backend with partial configurationcan be repeated; can also -backend-config="key=myapp/dev/terraform.tfstate"
terraform init -migrate-statemigrate existing state to the new backendinteractive confirmation; -force-copy skip confirmation in automation
terraform init -reconfigureignore old backend settings and reconfigure (without migrating)use when switching to another environment's key
-lock-timeout=DURATIONwait and retry when the lock cannot be acquiredrecommended in CI 5m; the default is 0 seconds, failing immediately
terraform force-unlock LOCK_IDDelete a stale lock-force skip confirmation; can only unlock the currently configured backend
terraform state pull / pushDownload / upload raw statepush checks lineage and serial; -force extremely dangerous
terraform workspace new/list/select/delete/showManage CLI workspacesterraform.workspace Returns the current name in code

Partial configuration file (dev.s3.tfbackend)

terraform {
  backend "s3" {}    # all parameters come from -backend-config; the code can be reused across environments
}
bucket = "tfstate"
key    = "myapp/dev/terraform.tfstate"
region = "us-east-1"      # S3-compatible storage must also specify a region name

endpoints = {
  s3 = "http://127.0.0.1:9000"
}
use_path_style              = true
skip_credentials_validation = true
skip_requesting_account_id  = true
skip_region_validation      = true
skip_metadata_api_check     = true
skip_s3_checksum            = true

use_lockfile = true
# Do not put access_key / secret_key here: use the environment variables AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY

Why not put credentials in tfbackend: The official documentation warns that values passed via -backend-config or hard-coded values are stored in the .terraform/ directory and in plan files. Use environment variables, a shared credentials file or (Lesson 5) OIDC for credentials.

export AWS_ACCESS_KEY_ID=rustfsadmin AWS_SECRET_ACCESS_KEY=rustfsadmin
terraform init -migrate-state -backend-config=dev.s3.tfbackend
Initializing the backend...
Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "local" backend to the
  newly configured "s3" backend. No existing state was found in the newly
  configured "s3" backend. Do you want to copy this state to the new "s3"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value: yes

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

How to verify:terraform state list you can still list all resources, and terraform plan no changes; in object storage you can see myapp/dev/terraform.tfstate. Common errors: Forgetting to export credentials → No valid credential sources found; writing the endpoint as https → TLS error. Production use: On AWS, remove all skip_* and endpoints, add encrypt = true,kms_key_id, enable versioning on the bucket and block public access (Lesson 4).

Locking-related

terraform plan -lock-timeout=60s     # wait up to 60 seconds if the lock cannot be acquired
terraform force-unlock 6f1a2c3e-8b0d-4e47-9a51-3c2d7e9f0b12
Do you really want to force-unlock?
  Terraform will remove the lock on the remote state.
  This will allow local Terraform commands to modify this state, even though it
  may still be in use. Only 'yes' will be accepted to confirm.

  Enter a value: yes

Terraform state has been successfully unlocked!

Actual storage location of the workspace

terraform workspace new scratch
terraform workspace list
terraform workspace select default && terraform workspace delete scratch
Created and switched to workspace "scratch"!
  default
* scratch
Switched to workspace "default".
Deleted workspace "scratch"!

Lab 2: S3-compatible backend + state migration + concurrent lock demo (about 10 min)

About MinIO The task originally planned to use a MinIO container. Verified 2026-11-15: the MinIO Community Edition GitHub repository was archived on 2026-04-25, the README states the community edition is “distributed only as source code” and no prebuilt versions are provided; the Docker Hub minio/minio repository returned 404 at the time of verification. Therefore below,uses RustFS 1.0.5 by default (Apache 2.0, S3-compatible, pullable from Docker Hub rustfs/rustfs ); if your company's image registry has a historical MinIO image, you can use option B; the Terraform-side configuration is exactly the same. Conditional writes (use_lockfile dependent) vary in support across S3-compatible implementations; step 5 will verify it in practice.
Start S3-compatible storage (listening on 127.0.0.1 only)
# Option A (default): RustFS 1.0.5 — the container runs as UID 10001; the data directory must be writable by it
mkdir -p ~/tf-lab/s3data ~/tf-lab/s3logs
sudo chown -R 10001:10001 ~/tf-lab/s3data ~/tf-lab/s3logs
docker run -d --name s3 --restart unless-stopped \
  -p 127.0.0.1:9000:9000 -p 127.0.0.1:9001:9001 \
  -v ~/tf-lab/s3data:/data -v ~/tf-lab/s3logs:/logs \
  rustfs/rustfs:1.0.5
export AWS_ACCESS_KEY_ID=rustfsadmin AWS_SECRET_ACCESS_KEY=rustfsadmin   # default credentials, for local lab use only

# Option B: if you have a historical MinIO image (replace the image address with your internal registry)
# docker run -d --name s3 -p 127.0.0.1:9000:9000 -p 127.0.0.1:9001:9001 \
#   -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD='change-me-123' \
#   -v ~/tf-lab/s3data:/data REGISTRY/minio/minio:RELEASE.2025-10-15T17-29-55Z \
#   server /data --console-address ":9001"
# export AWS_ACCESS_KEY_ID=minioadmin AWS_SECRET_ACCESS_KEY='change-me-123'

docker ps --filter name=^s3$ --format '{{.Names}} {{.Status}}'
s3 Up 5 seconds

The console is at http://127.0.0.1:9001 (on an Azure VM, available via ssh -L 9001:127.0.0.1:9001 port forwarding). For how to change RustFS's default credentials, follow its official documentation; never use default credentials in production.

Create the bucket and enable versioning (using the official AWS CLI container; independent of the specific storage implementation)
alias s3cli='docker run --rm --network host -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION=us-east-1 amazon/aws-cli --endpoint-url http://127.0.0.1:9000'
s3cli s3 mb s3://tfstate
s3cli s3api put-bucket-versioning --bucket tfstate --versioning-configuration Status=Enabled
s3cli s3api get-bucket-versioning --bucket tfstate
make_bucket: tfstate
{
    "Status": "Enabled"
}

Versioning lets you retrieve the previous version after state is overwritten by mistake (the state recovery in Lesson 7 uses this). If the implementation you use does not support the versioning API, note it and continue the lab.

Write the backend configuration and migrate state (writing the backend.tf and dev.s3.tfbackend into ~/tf-lab/myapp)
cd ~/tf-lab/myapp
terraform init -migrate-state -backend-config=dev.s3.tfbackend
terraform state list | wc -l
terraform plan -detailed-exitcode; echo "exit=$?"
s3cli s3 ls s3://tfstate --recursive
mkdir -p ~/tf-lab/backup && mv terraform.tfstate* ~/tf-lab/backup/ 2>/dev/null; ls
Successfully configured the backend "s3"! ...
10
No changes. Your infrastructure matches the configuration.
exit=0
2026-11-15 10:21:07      21874 myapp/dev/terraform.tfstate
backend.tf  dev.s3.tfbackend  main.tf  modules  moved.tf  versions.tf

10 resources = 5 each from m1's stack and stack_staging. After a successful migration, the local terraform.tfstate is no longer used; moving the backup aside avoids accidental future use. .terraform/terraform.tfstate is the backend configuration cache (not your infrastructure state); do not delete or commit it.

Concurrent lock demo (open two terminals)
cd ~/tf-lab/myapp
terraform apply -var external_port=8080
# Stop at the "Enter a value:" prompt and do not type — A holds the lock the whole time
cd ~/tf-lab/myapp
s3cli s3 ls s3://tfstate/myapp/dev/
terraform plan
2026-11-15 10:25:41        231 terraform.tfstate.tflock
2026-11-15 10:21:07      21874 terraform.tfstate
╷
│ Error: Error acquiring the state lock
│
│ Error message: operation error S3: PutObject, https response error
│ StatusCode: 412, RequestID: 1878F2A9C3D4E5F6, api error PreconditionFailed:
│ At least one of the pre-conditions you specified did not hold
│ Lock Info:
│   ID:        6f1a2c3e-8b0d-4e47-9a51-3c2d7e9f0b12
│   Path:      tfstate/myapp/dev/terraform.tfstate
│   Operation: OperationTypeApply
│   Who:       student@lab-vm
│   Version:   1.17.2
│   Created:   2026-11-15 10:25:41.118 +0000 UTC
│   Info:
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.
╵

Then run in B terraform plan -lock-timeout=120s (it will hang waiting), then return to A and enter no to cancel: A releases the lock, B immediately acquires it and completes the plan. The exact error wording depends on the storage implementation (the RequestID and error code text may differ); the key points are 412 / PreconditionFailed and Lock Info. If B does not error and instead starts the plan right away, your storage implementation does not support conditional writes,use_lockfile so the lock is ineffective on that implementation — this is exactly what “best effort” means; in production, use AWS S3 or a verified implementation.

Create and clear a stale lock
terraform apply      # stop at the confirmation prompt
pkill -9 -f "terraform apply"        # simulate the CI runner being forcibly reclaimed
s3cli s3 ls s3://tfstate/myapp/dev/   # .tflock still exists
terraform plan 2>&1 | grep -E "ID:|Who:|Created:"
# After confirming the process for Who really no longer exists:
terraform force-unlock -force 6f1a2c3e-8b0d-4e47-9a51-3c2d7e9f0b12
s3cli s3 ls s3://tfstate/myapp/dev/
2026-11-15 10:31:02        231 terraform.tfstate.tflock
2026-11-15 10:21:07      21874 terraform.tfstate
│   ID:        0c7d9e21-55aa-4f0b-8d3e-77b1c2a4e9f0
│   Who:       student@lab-vm
│   Created:   2026-11-15 10:31:02.554 +0000 UTC
Terraform state has been successfully unlocked!
2026-11-15 10:21:07      21874 terraform.tfstate

The lock ID in the example differs each time; copy the ID from your own output.

Experience the workspace “pitfall”
terraform workspace new scratch
terraform plan 2>&1 | grep -E "Plan:|will be created" | head -3
terraform apply -auto-approve 2>&1 | grep -m1 -i "conflict"
  # module.stack.docker_container.app will be created
Plan: 10 to add, 0 to change, 0 to destroy.
│ Error: Unable to create container: Error response from daemon: Conflict. The container name "/myapp" is already in use by container "4c1f9e…"

The new workspace's state is empty, so Terraform wants to create another set of containers with the same names, which conflicts with the containers in the default workspace (if some objects have already been created, run terraform destroy -auto-approve to clean up the resources in scratch). To make workspaces usable, every name must include terraform.workspace. Cleanup:

terraform destroy -auto-approve      # only destroys objects already created in the scratch workspace
terraform workspace select default
terraform workspace delete scratch
git add -A && git commit -qm "m2: s3 backend (partial config)"

Case 1: CI concurrent pipelines overwrite each other's state

Problem: Two merges triggered apply at almost the same time; the old backend had no lock configured, so the apply that finished later overwrote the state using the old serial, and a newly created security group vanished from state; the next plan tried to create it again and failed. Approach: Enable locking (S3 use_lockfile / azurerm lease); add to every command in CI -lock-timeout=10m, and serialize runs for the same environment at the pipeline level (GitHub Actions concurrency concurrency group). Limitation: Locking only protects state writes, not “two plans based on different code versions” — apply must use the plan file saved in the same pipeline (Lesson 5).

Case 2: migrating from DynamoDB locking to S3 native locking

Problem: After upgrading to 1.11+,dynamodb_table deprecation warnings appear. Approach: Phase 1: set both dynamodb_table and use_lockfile = true (both locks are acquired). After all pipelines and engineers have upgraded to 1.11+, phase 2 removes dynamodb_table and terraform init -reconfigure, and finally deletes the DynamoDB table. The IAM policy must allow <key>.tflock to perform s3:PutObject/s3:DeleteObject. Limitation: Older Terraform versions do not recognize use_lockfile, so versions must be unified first (m8's required_version).

Case 3: one state manages 600 resources, and plan takes 9 minutes

Problem: Networking, databases and apps are all in one root module; any change requires refreshing all resources, lock hold times are long, and the team queues up. Approach: Split by component into three root modules and three keys (network / data / app); app obtains the network ID through variables or a data source; use m4's removed { lifecycle { destroy = false } } + the new root module's import blocks to complete the migration. Limitation: After splitting, cross-component changes must be applied in order; avoid “one component depending on another component's entire state” (terraform_remote_state requires permission to read the entire state).

Common errors and fixes

Error: Error acquiring the state lock ... StatusCode: 412 ... PreconditionFailed ... Lock Info: ID: … Operation: OperationTypeApply

Cause: Someone (or a CI job) is holding the lock; or a previous process exited abnormally and left a stale lock.

s3cli s3 cp s3://tfstate/myapp/dev/terraform.tfstate.tflock - | python3 -m json.tool   # check Who / Created
ps -ef | grep "[t]erraform"     # on the machine shown in Who, check whether the process exists

Fix: If the other side is still running → wait, or use -lock-timeout; once the process is confirmed gone → terraform force-unlock LOCK_ID. Prevention: Set timeouts and concurrency groups in CI; do not use interactive apply in CI.

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

Cause:.terraform/terraform.tfstate The backend configuration cached in is different from this run (the key or tfbackend file changed).

Fix: To migrate state → terraform init -migrate-state …; just switching to another environment → terraform init -reconfigure -backend-config=staging.s3.tfbackend. When in doubt, first terraform state pull > backup.tfstate.

Error: No valid credential sources found ... failed to refresh cached credentials, no EC2 IMDS role found

Cause: Credentials were not exported: AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY; the SDK tried environment variables, the shared credentials file and IMDS in turn, and all failed.

Fix: Export the credentials; for an S3-compatible endpoint, confirm that skip_metadata_api_check = true is set.

Error: Variables not allowed ... on backend.tf line 3, in terraform: key = "${var.env}/terraform.tfstate"

Cause: The backend block is initialized before variables are loaded, so it cannot reference variables / locals.

Fix: Switch to partial configuration: backend "s3" {} + -backend-config file or -backend-config="key=dev/terraform.tfstate".

Error: Failed to save state ... Error saving state: failed to upload state: ... XAmzContentSHA256Mismatch / InvalidArgument

Cause: The newer AWS SDK's default checksum headers are not supported by some S3-compatible implementations.

Fix: Set in the backend configuration skip_s3_checksum = true. If apply has finished but the state was not saved, Terraform writes the state to a local errored.tfstate file — after fixing the backend, use terraform state push errored.tfstate to upload it,and never delete this file.

Command-line tasks
1. Switch the current directory from dev's key to staging's key (staging already has its own state), without migrating any data.
terraform init -reconfigure -backend-config=staging.s3.tfbackend
terraform state list
2. Run plan in CI: wait up to 5 minutes if the lock cannot be acquired, and use whether there are changes as the exit code.
terraform plan -lock-timeout=5m -detailed-exitcode -out=tfplan; rc=$?
# rc=0 no changes; rc=2 changes; rc=1 failure
Scenario analysis
The overnight apply pipeline timed out and was forcibly terminated by the platform; in the morning everyone's plan reports “Error acquiring the state lock”. The on-call colleague is about to directly force-unlock. What would you check first? What else must be done after unlocking?

First look at Who / Created / Operation in Lock Info, and confirm that the corresponding runner process has really terminated (the platform console,ps); confirm that no other re-run jobs are in progress. Immediately after unlocking, terraform plan: the apply may have been half-finished — some resources were created and the state periodically persisted partial results; some resources may have been created without being written to state (in that case plan will try to create them again and report “already exists”). Based on the plan results, use import blocks to bring orphaned resources under management (m4), and check whether there are errored.tfstate, and if necessary restore the state from the bucket's version history.

Verified teaching videos

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · its remote backend (S3 + DynamoDB) chapter explains the motivation for remote state; note that DynamoDB locking was still mainstream when this video was recorded and is now deprecated — follow this lesson's use_lockfile instead

No verified video specifically explaining S3 native locking use_lockfile was found; a storyboard script is provided below.

Official documentation

Video storyboard script (about 100 seconds)

These course materials cannot directly generate a video/MP3; a storyboard and narration script are provided for a video tool to generate.

Shot 1 · 0–20s
Visual: two laptops each have a terraform.tfstate; the serial numbers become 8 and 9, and a crack appears between them.
Narration: local state starts diverging as soon as a second person joins. The team needs one shared ledger.
Shot 2 · 20–50s
Visual: terraform.tfstate appears in the bucket; A sends PutObject with an If-None-Match asterisk, and a yellow tflock file appears in the bucket.
Narration: with use_lockfile enabled, Terraform uses S3's conditional write to create the lock file. The write succeeds only if the file does not exist; success means the lock is acquired.
Shot 3 · 50–75s
Visual: B sends the same request and gets a red 412; Lock Info pops up on screen: ID, Who, Created.
Narration: the second person gets 412, precondition failed. Terraform reads the lock info and tells you who is operating.
Shot 4 · 75–100s
Visual: A's process is forcibly killed and the tflock file stays in the bucket; the on-call person confirms the process is gone, runs force-unlock, and the file disappears.
Narration: an abnormal exit leaves a stale lock. Confirm the other side is really no longer running, then run force-unlock, and immediately re-run plan to check the state.
or score ≥ 70% on the quiz

Module 3 · count, for_each and dynamic

15:00 – 22:00 · When one resource block becomes multiple instances, each instance's “key” is its ID in state — whether you use an index or a name determines whether deleting one element drags down a whole group
7 minmodule for_each 0.13+ · moved 1.1+★★★★☆
Learning goals
  • Write the count,for_each instances' full addresses ([0] and ["web1"]), and explain why deleting a middle element from a list makes count the plan replace all the instances after it.
  • Know when to use count (0/1 switches, identical copies), and when to use for_each (instances with identity); know that for_each 's keys must be known at plan time and cannot be sensitive values.
  • Use moved block to migrate myapp's multi-instance setup losslessly from count to for_each; use dynamic block to generate nested blocks from a map (container labels).
Prerequisites: m1's modules, and Lesson 1's for expressions and toset(). Importance:★★★★☆

What: three “repetition” mechanisms

MechanismApplies toInstance keyReference style
count = Nresource, data, moduleinteger index [0]…[N-1]count.index; external docker_container.app[0],docker_container.app[*].name
for_each = map / set(string)resource, data, modulestring key ["web1"]each.key,each.value; external docker_container.app["web1"], the whole resource is a map
dynamic "block name" { for_each = … }Resource inside nested blocks (ports, labels, volumes, ingress…)does not create state instances; it only generates multiple nested blocksThe iterator variable defaults to the same name as the block: labels.key,labels.value (can be renamed with iterator iterator)

Why: why addresses matter more than you think

Each instance in state is stored by its address. Using count = length(var.names) ,[1] means “the second element of the list”. After deleting the second element of the list, the original third element becomes [1]: Terraform sees [1] 's name change from web2 to web3 (the container name is a ForceNew attribute → replacement),[2] disappears from the code (destroy). You only wanted to delete one, but the result is “replace one, destroy one”,and web3 needlessly restarted once. Switching to for_each, deleting "web2" will only destroy ["web2"], and the other keys are unaffected.

How: how Terraform expands instances

  1. At plan time, first evaluate count/for_each expression to get the set of instance keys. This value must be known at plan time: it cannot depend on attributes that are only known after apply (for example another resource's ID), otherwise it reports Invalid for_each argument.
  2. The key set is compared with the instance keys the resource already has in state: present on both sides → compare attributes (no-op / update / replace); only in code → create; only in state → destroy.
  3. for_each 's keys cannot be sensitive values (keys appear in addresses and the UI). A list first needs to be toset(); object lists are often converted to a map: { for s in var.svcs : s.name => s }.
  4. Adding to a resource that has no count count , Terraform automatically treats the original keyless instance as [0]; but when changing from count to for_each, or changing key names,does not automatically match, so you must write moved.

When: how to choose

  • count: conditional creation (count = var.enable_redis ? 1 : 0); identical copies with no independent identity that can be scaled down from the end at any time.
  • for_each: each instance has a name or its own configuration (multiple containers, subnets or users) — the majority of production scenarios.
  • dynamic: use when the number of nested blocks is determined by input; do not write every nested block as dynamic just to look generic, as readability drops significantly.
  • Module-level for_each: module "stack" { for_each = var.envs … } can deploy several stacks at once; the addresses become module.stack["dev"]. Note, however: it is best to isolate state between environments (m2), so module-level for_each is better suited to “multiple components of the same kind within one environment”.

Comparison with similar technologies

Terraform for_eachBicepCloudFormationPulumi
Loop syntaxfor_each / count[for x in list: {...}] (by index)Fn::ForEach (language extension)Host-language loops
Instance identitymap keyindex / name at deploy timeLogical IDResource name (URN)
Rename migrationmoved blockIn Azure, just keep the resource name unchangedNone (requires replacement or import)aliases
Common misconceptions① “count Changing to for_each Terraform automatically matches by order” — no,[0] and ["web1"] are completely different addresses; without moved, everything is destroyed and recreated. ② “for_each can use a list directly” — it must be a map or set(string), a list must be toset(), while a set has no order and its elements must be unique. ③ “Using count when [*] is convenient, so for_each is not good” — for_each resources should use values(docker_container.app)[*].name or for expressions [for c in docker_container.app : c.name]. ④ “dynamic blocks create instances in state” — no; it only generates nested blocks and has nothing to do with addresses.

Comparison diagram: count vs for_each plan when deleting a middle element

count = length(["web1","web2","web3"]) → delete "web2" for_each = toset(["web1","web2","web3"]) → delete "web2" state (before)code (after) app[0] = web1 app[1] = web2 app[2] = web3 app[0] = web1 ✓ app[1] = web3 -/+ app[2] destroyed Result: 1 replace + 1 destroy (web3 is needlessly recreated) state (before)code (after) app["web1"] app["web2"] app["web3"] app["web1"] ✓ app["web2"] destroyed app["web3"] ✓ Result: only web2 is destroyed
Figure 3-1: count matches by position, for_each matches by key

Flowchart: safe migration from count → for_each

1. List existing instancesstate list / state show 2. Design keys and attributesKeep name and port unchanged 3. Change to for_each + moved[0] → ["web1"] … 4. The plan must contain only moved0 add / 0 destroy 5. apply + commitKeep the moved blocks for a while If -/+ appears? That means a ForceNew attribute (such as name) changed → go back to step 2
Figure 3-2: moved only solves the “address” problem; replacements caused by attribute changes are avoided by keeping attributes consistent

Interactive simulator: delete one instance and see how the plan is written

Choose a mode and click “delete” on an instance; the simulator computes each instance's action using Terraform's matching rules (count by index, for_each by key). A container name is an attribute that means “any change = replace” in the docker provider.

terraform plan

Core syntax and commands

Syntax / commandPurposeNotes
count = var.enabled ? 1 : 0Conditional creationWhen referencing one(docker_container.x[*].id) can yield null or the value when 0/1
for_each = var.instancesCreate from a mapeach.key / each.value.port
for_each = toset(var.names)Create from a set of stringseach.key == each.value
{ for k, c in docker_container.app : k => c.name }Convert instance map into outputA for_each resource is itself a map
dynamic "labels" { … }Generate nested blocks from a collectioncontent { label = labels.key value = labels.value }
terraform state list 'module.stack.docker_container.app'List all instancesin shell, when the address contains quotes, wrap the whole address in single quotes
terraform state show 'module.stack.docker_container.app["web1"]'View a single instanceWindows PowerShell requires writing it as '…app[\"web1\"]'
# dynamic: turns a map into multiple labels nested blocks
variable "labels" {
  type    = map(string)
  default = { "com.example.team" = "platform", "com.example.env" = "dev" }
}

resource "docker_container" "app" {
  # ...
  dynamic "labels" {
    for_each = var.labels
    content {
      label = labels.key
      value = labels.value
    }
  }
}
terraform console
> toset(["web1", "web2", "web1"])
> { for i, n in ["web1", "web2"] : n => { port = 8080 + i } }
> exit
toset([
  "web1",
  "web2",
])
{
  "web1" = {
    "port" = 8080
  }
  "web2" = {
    "port" = 8081
  }
}

How to verify: After changing to for_each, first terraform plan, every instance in the output should show “has moved to”; Common errors: a key uses a value only known after apply (such as docker_network.this.id) → Invalid for_each argument; Production use: Subnets, DNS records, IAM users, alert rules and other “named collections” should always use for_each.

Lab 3: myapp multi-instance, migrating from count to for_each (about 8 min)

First expand to 3 instances with count: edit modules/stack
variable "app_count" {
  description = "Number of application containers"
  type        = number
  default     = 1
}
resource "docker_container" "app" {
  count   = var.app_count
  name    = count.index == 0 ? var.name_prefix : "${var.name_prefix}-${count.index}"
  image   = docker_image.app.image_id
  restart = "unless-stopped"
  env     = [for k, v in local.app_env : "${k}=${v}"]
  ports {
    internal = 5000
    external = var.external_port + count.index
  }
  networks_advanced {
    name = docker_network.this.name
  }
}
output "container_names" {
  value = concat(docker_container.app[*].name, [docker_container.redis.name])
}
# In the root module, in module "stack", add one line: app_count = 3
terraform plan | grep -E "^  # |Plan:"
  # module.stack.docker_container.app has moved to module.stack.docker_container.app[0]
  # module.stack.docker_container.app[1] will be created
  # module.stack.docker_container.app[2] will be created
  # module.stack_staging.docker_container.app has moved to module.stack_staging.docker_container.app[0]
Plan: 2 to add, 0 to change, 0 to destroy.

Note the first line: adding count Terraform automatically treats the original keyless instance as [0]. app_url The output still references var.external_port, so no change is needed for now.

terraform apply -auto-approve
docker ps --format '{{.Names}} {{.Ports}}' | grep -E '^myapp(-[0-9])? '
myapp-2 0.0.0.0:8082->5000/tcp
myapp-1 0.0.0.0:8081->5000/tcp
myapp 0.0.0.0:8080->5000/tcp
Feel the pain point of count: the requirement is “take myapp-1 offline, keep myapp-2”. This can't be done with count — changing app_count to 2 only deletes the last one [2] (myapp-2). If you switch to driving count from a list of names, deleting a middle element triggers “replace + destroy” (you can verify this on the “Animation” page). Do not apply this step, and go straight to the migration.
Change to for_each, and use moved to map the old indices
variable "app_instances" {
  description = "Application instances: the key is the instance ID; when name is omitted it is <name_prefix>-<key>"
  type = map(object({
    port = number
    name = optional(string)
  }))
  default = { web1 = { port = 8080 } }
}
resource "docker_container" "app" {
  for_each = var.app_instances
  name     = coalesce(each.value.name, "${var.name_prefix}-${each.key}")
  image    = docker_image.app.image_id
  restart  = "unless-stopped"
  env      = [for k, v in local.app_env : "${k}=${v}"]
  ports {
    internal = 5000
    external = each.value.port
  }
  networks_advanced {
    name = docker_network.this.name
  }
}

moved {
  from = docker_container.app[0]
  to   = docker_container.app["web1"]
}
moved {
  from = docker_container.app[1]
  to   = docker_container.app["web2"]
}
moved {
  from = docker_container.app[2]
  to   = docker_container.app["web3"]
}
output "app_urls" {
  value = { for k, v in var.app_instances : k => "http://localhost:${v.port}" }
}

output "container_names" {
  value = concat([for c in docker_container.app : c.name], [docker_container.redis.name])
}
module "stack" {
  source      = "./modules/stack"
  name_prefix = "myapp"
  app_image   = var.app_image
  app_instances = {
    web1 = { port = 8080, name = "myapp" }     # keep the old name to avoid replacement
    web2 = { port = 8081, name = "myapp-1" }
    web3 = { port = 8082, name = "myapp-2" }
  }
}

module "stack_staging" {
  source        = "./modules/stack"
  name_prefix   = "myapp-stg"
  env           = { APP_ENV = "staging" }
  app_instances = { web1 = { port = 8090, name = "myapp-stg" } }
}

output "url" {
  value = module.stack.app_urls["web1"]
}
output "staging_url" {
  value = module.stack_staging.app_urls["web1"]
}

The root module's external_port variables are no longer used and can be deleted. Module-internal moved blocks apply to each module instance: staging only has [0], so the other two moved blocks find no from, and they are silently ignored.

The plan must contain only moved, then apply
terraform plan | grep -E "^  # |Plan:"
terraform apply -auto-approve
  # module.stack.docker_container.app[0] has moved to module.stack.docker_container.app["web1"]
  # module.stack.docker_container.app[1] has moved to module.stack.docker_container.app["web2"]
  # module.stack.docker_container.app[2] has moved to module.stack.docker_container.app["web3"]
  # module.stack_staging.docker_container.app[0] has moved to module.stack_staging.docker_container.app["web1"]
Plan: 0 to add, 0 to change, 0 to destroy.
Now you can take only web2 offline: remove from the root module's app_instances delete web2 one line
terraform plan | grep -E "^  # |Plan:"
terraform apply -auto-approve
git add -A && git commit -qm "m3: for_each instances with moved"
  # module.stack.docker_container.app["web2"] will be destroyed
Plan: 0 to add, 0 to change, 1 to destroy.
(Optional) dynamic labels: add a labels variable to the module (see the “Commands” page), and in docker_container.app , add dynamic "labels". The plan will show the container needs to be replaced (Docker labels cannot be changed after creation), which also shows: before using dynamic, first check the provider documentation for which attributes are ForceNew. The lab environment can apply; in production, schedule a change window.

Case 1: deleting one subnet causes the entire AKS node pool to be rebuilt

Problem: Subnets were created using count = length(var.subnet_cidrs) , and after deleting an unused subnet in the middle of the list, the plan showed the two subnets after it being replaced — one of which hosts the AKS node pool. Approach: Immediately stop the apply; change the subnets to for_each = var.subnets (a map: name → CIDR), write a moved for each old index, then delete the unused keys. Limitation: Before migrating, you must confirm that each key maps one-to-one to the actual resources (terraform state show check each CIDR).

Case 2: for_each depends on a value only known after apply

Problem:for_each = toset(azurerm_storage_account.logs[*].id) The first plan reports Invalid for_each argument. Approach: Change the keys to static values known in the code (such as the logical name of the storage account) and put the ID into the value: for_each = { for k, sa in azurerm_storage_account.logs : k => sa.id }— the map's keys come from keys known to for_each; the values can be unknown. Limitation: Avoid using -target a “temporary workaround” that requires two applies, as it makes the pipeline non-repeatable.

Case 3: managing DNS and alerts for 40 microservices with module-level for_each

Problem: Each service needs one DNS record and two alerts; copy-pasting easily leads to omissions. Approach:module "svc" { for_each = local.services … },local.services by reading a YAML file yamldecode(file("services.yaml")) ; service teams change the YAML via PRs. Limitation: 40 × N resources in one state will slow down plans; split the root module by team when needed (m2).

Common errors and fixes

Error: Invalid for_each argument ... The "for_each" map includes keys derived from resource attributes that cannot be determined until apply

Cause: The key depends on a value known only after apply.

Fix: Use static known values for keys (variables, literals, keys of other for_each); put unknown values in value.

Error: Invalid for_each argument ... The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type list of string.

Fix:for_each = toset(var.names); convert the object list to a map: { for o in var.items : o.name => o }.

Error: Missing resource instance key ... Because docker_container.app has "for_each" set, its attributes must be accessed on specific instances.

Cause: A multi-instance resource is referenced as if it were a single resource (such as docker_container.app.name).

Fix:docker_container.app["web1"].name, or [for c in docker_container.app : c.name].

Error: Invalid for_each argument ... Sensitive values, or values derived from sensitive values, cannot be used as for_each arguments.

Fix: Do not use sensitive values as keys; when necessary, for_each = nonsensitive(toset(keys(var.secret_map)))— only do this when you have confirmed that the key itself is not sensitive.

plan shows # module.stack.docker_container.app["web1"] must be replaced ... ~ name = "myapp" -> "myapp-web1" # forces replacement

Cause: moved matched the address, but a ForceNew attribute such as the name changed.

Fix: Keep the old attribute (this lab uses name = "myapp" to override), or accept the replacement and schedule a window.

Command-line tasks
1. Use the console to convert ["web1","web2"] into a map keyed by name, with ports incrementing from 8080.
echo '{ for i, n in ["web1","web2"] : n => { port = 8080 + i } }' | terraform console
2. In bash, view the for_each instance web3 's detailed attributes.
terraform state show 'module.stack.docker_container.app["web3"]'
Scenario analysis
In the code, resource "azurerm_linux_virtual_machine" "vm" { count = 3 … name = "vm-${count.index}" }, now vm-1 needs to be permanently taken offline, and the other two must not be rebuilt. Give the steps.

① Change to for_each = toset(["vm-0","vm-2"]) (or a map),name = each.key; ② write moved { from = …vm[0] to = …vm["vm-0"] } and moved { from = …vm[2] to = …vm["vm-2"] }; ③ do not add [1] a moved for it, and it will be planned for destruction; ④ confirm in the plan: 2 moved, 1 destroy, 0 replace; ⑤ if vm-1 still has a data disk that must be kept, first confirm how the disk resource is handled (when it is a separate resource, its address is handled the same way).

Verified teaching videos

▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · introductory course with basic count / for_each demonstrations; for migration and moved, this lesson takes precedence

No verified video specifically about “migrating count to for_each” was found; a storyboard script is provided.

Official documentation

Video storyboard script (about 80 seconds)

These course materials cannot directly generate a video/MP3; a storyboard and narration script are provided for a video tool to generate.

Shot 1 · 0–20s
Visual: three boxes labeled 0, 1, 2 contain web1, web2, web3; the middle box is removed, the box on the right slides into position 1 and turns yellow.
Narration: count keeps track by position. Remove the middle one, and everything after it must move; moving means rebuilding.
Shot 2 · 20–45s
Visual: the same three boxes, but labeled with the names web1, web2, web3; remove web2, the others stay put.
Narration: for each keeps track by name. Deleting one name only affects that name.
Shot 3 · 45–80s
Visual: three moved blocks appear in the code editor, with arrows from app[0] pointing to app["web1"]; plan outputs “has moved to”, and the final line “0 to destroy” is highlighted.
Narration: migrating from count to for each requires moved blocks to map each old index to a new key, while keeping attributes such as the name unchanged.
or score ≥ 70% on the quiz

Module 4 · Refactoring: moved, import, removed blocks

22:00 – 30:00 · Three declarative “state surgery” blocks: rename without rebuilding, bring existing resources under management, stop managing without deleting — all written in code, go through PR, and can be previewed by plan
8 minmoved 1.1 · import 1.5 · removed 1.7-generate-config-out is marked as experimental in the documentation★★★★★
Learning goals
  • Explain moved 's mechanism: at the start of plan, the old addresses in state are rewritten to new addresses in memory, and the provider sees an “existing object” rather than a “new object”; write moved at the resource, instance and module granularities.
  • Use import block (can include for_each) + terraform plan -generate-config-out=generated.tf to bring manually created resources under management, and clean up the generated configuration.
  • Use removed block + lifecycle { destroy = false } to remove resources from state without destroying them; be able to compare terraform state mv/rm,terraform import commands' pros and cons and make a choice.
Prerequisites: moved as used in m1 and m3. Importance:★★★★★ (essential for production refactoring and state splitting)

What: three blocks, three intents

BlockIntentMinimal syntaxIntroduced inEquivalent old command
movedsame object changes address (rename, move into/out of module, count→for_each, cross-type*)moved { from = A to = B }1.1 (cross-resource-type 1.8, requires provider support)terraform state mv A B
importbring an existing real object into stateimport { to = ADDR id = "…" }1.5 (for_each 1.7)terraform import ADDR ID
removedremove a resource from code and specify whether the real object is destroyedremoved { from = ADDR lifecycle { destroy = false } }1.7terraform state rm ADDR

Why: why use blocks instead of commands

  • Reviewable: blocks are written in code, go through PR, and reviewers can see “has moved to / will be imported / will no longer be managed” in the plan. Commands immediately change state in someone's terminal, leaving no record.
  • Replicable to all environments: dev, staging and prod each have their own state. With commands you must run them manually in each environment (and in an order matching the code merge timing); with blocks, the next apply in each environment completes automatically after the code is merged.
  • Atomicity: blocks are computed in the same plan as other changes and committed in the same apply; state mv if the code has not been merged afterward, other people's plans will show strange results.
  • The module author's only option: when publishing a new module version, the author cannot run commands on callers' state, so the only option is to write moved blocks in the module.

How: internal mechanics

moved

  1. Before plan starts refreshing, Terraform core collects all moved statements across modules and validates: to the to address must exist in the configuration; from the from address must not still exist in the configuration; cycles are not allowed; chained moved (A→B, B→C) are merged in order.
  2. For each match in state from object: if to address has no object in state yet, the address is changed in memory to to. If to is already occupied, this moved is ignored and a warning is issued. from If it does not exist, it is silently skipped (so moved blocks in a module are harmless to new users).
  3. After that the flow is the same as a normal plan: the provider's PlanResourceChange receives “prior state” that is the original object, so identical attributes mean no-op. The plan output # A has moved to B.
  4. On apply, the new address is written to state (serial + 1). does not call the provider's ApplyResourceChange— the real object is not touched at all.

import block

  1. At plan time, for each import block, call the provider's ImportResourceState(id), then ReadResource read all attributes of the real object.
  2. Compare with the configuration: if the configuration matches the real object → “will be imported”; if there are differences → “will be imported” plus an update shown at the same time (or even a replacement! Look carefully).
  3. If the configuration does not exist and you use -generate-config-out=FILE: Terraform generates resource blocks from the attributes it read and writes them to FILE (supports only root module resources; FILE must not already exist). The generated configuration needs manual cleanup: remove default values and read-only attributes, and change values to reference variables.
  4. After apply the object is written to state. The import block then becomes a no-op; you can keep it as a historical record or delete it.

removed block

  • from points to a resource or module (cannot include an instance key, i.e. you cannot remove only app["web2"]); the resource itself must already be deleted from the configuration.
  • destroy = false: removes it only from state; the real object is kept (the plan shows “will no longer be managed by Terraform”); destroy = true (default): same effect as deleting the code directly, but you can attach a destroy-time local-exec/remote-exec provisioner.

When: which one to choose

ScenarioRecommendedNotes
rename a resource / module call, move into a module, count→for_eachmovedmake sure attributes are unchanged, otherwise replacement still happens
bring under management objects created manually or by other toolsimport block (+ -generate-config-out)Run plan first to see differences, then decide whether to change the code or accept the change
Split state: move a resource from root module A to root module BIn A, use removed { destroy = false } + in B, use importmoved cannot cross states; first import in B and apply, then remove in A
hand a resource to another team / toolremoved { destroy = false }the other side takes it over with import
emergency fixes, one-off, single-person environmentsstate mv/rm (first -dry-run, first state pull back up)you must still fix the corresponding code afterward

Comparison with similar technologies

Terraform blocksstate commandsPulumiCloudFormation
Rename without rebuildingmovedstate mvaliasesNot supported (requires Retain + import)
Bring existing objects under managementimport block + generated configterraform importpulumi import (generated code)Resource import / IaC generator
Stop managingremovedstate rmpulumi state delete / retainOnDeleteDeletionPolicy: Retain
Common misconceptions① “moved renames the real resource” — no, it only changes the address in state; container names and Azure resource names are determined by attributes, and attribute changes still cause updates or replacements. ② “After an import block is applied, the code matches the real resource” — import only puts the object into state; if the configuration differs from the real attributes, the same apply will modify the real resource. ③ “Delete moved blocks as soon as they have been used” — for module authors, moved blocks must be kept long-term (callers may skip several versions before upgrading); for root modules, keep them at least until every environment has applied. ④ “removed You can stop managing just one for_each instance” — no,from cannot include an instance key; when needed, use terraform state rm 'addr["key"]'.

Architecture diagram: where moved sits in the plan pipeline

Read stateGetObject / local file Apply moved statementsRewrite addresses in memory Refresh ReadResourceRead the real object by the new address PlanResourceChangeprior = original object → no-op apply: write state onlyserial+1, no cloud API calls state (in memory) docker_container.app id=4c1f9e… ↓ moved module.stack.docker_container.app["web1"] id=4c1f9e… ID unchanged → same real container If there is no moved docker_container.app: not in configuration → plan destroy …app["web1"]: not in state → plan create ApplyResourceChange × 2 (delete container, create container) → downtime; resources with data → data loss
Figure 4-1: moved happens before refresh and plan; it only changes the state “index”, not the object itself

Flowchart: splitting state (removed + import combined)

Root module A (myapp/dev)Delete the module "staging" coderemoved { from = module.staging lifecycle { destroy = false } }Step ② apply Real objects in Dockermyapp-stg · myapp-stg-redismyapp-stg-netalways running, never rebuilt Root module B (myapp/staging)module "stack" with the same parametersimport { to = module.stack.… id = … }plan: only import, 0 changeStep ① apply Take over Let go
Figure 4-2: import into the new state first (no changes allowed during the brief window of dual management), then remove from the old state; no step touches the real object

Core animation: how moved blocks map state addresses to new addresses

Scenario: move the 5 resources in the root module into module.stack, and change docker_container.app to for_each instances ["web1"]. Toggle “with / without moved blocks” to compare the calls between Terraform core and the provider.

objects in state (address → object ID)
resource addresses in configuration

Core blocks and commands

Block / commandPurposeKey points
moved { from to }Address migrationCan be used for resources, instances ([0],["k"]), module call (module.a → module.b)
import { to id }Importid format is determined by the provider (see the Import section of the resource docs); can be written for_each
terraform plan -generate-config-out=generated.tfto generate resource blocks for imports that lack configurationonly supports the root module; the file must not already exist
removed { from lifecycle { destroy = false } }Stop managingfrom without instance key
terraform state mv -dry-run A BPreview imperative migrationRemote backends also acquire locks
terraform state rm -dry-run ADDRPreview removal from statereal object is kept
terraform state pull > backup.tfstateBack up before surgeryBackup files contain sensitive information; store them securely

Three granularities of moved

# 1) rename a resource
moved {
  from = docker_image.app
  to   = docker_image.myapp
}

# 2) instance key change (count → for_each)
moved {
  from = docker_container.app[0]
  to   = docker_container.app["web1"]
}

# 3) rename an entire module call (all resources inside the module migrate together)
moved {
  from = module.stack_staging
  to   = module.staging
}

import block: single and for_each

import {
  to = docker_volume.redis_data
  id = "myapp-redis-data"            # the import ID for docker_volume is the volume name
}

# 1.7+: batch import
import {
  for_each = { logs = "myapp-logs", cache = "myapp-cache" }
  to       = docker_volume.extra[each.key]
  id       = each.value
}
terraform plan -generate-config-out=generated.tf
cat generated.tf
docker_volume.redis_data: Preparing import... [id=myapp-redis-data]
docker_volume.redis_data: Refreshing state... [id=myapp-redis-data]

Terraform will perform the following actions:

  # docker_volume.redis_data will be imported
  # (config will be generated)
    resource "docker_volume" "redis_data" {
        driver      = "local"
        driver_opts = {}
        id          = "myapp-redis-data"
        mountpoint  = "/var/lib/docker/volumes/myapp-redis-data/_data"
        name        = "myapp-redis-data"
    }

Plan: 1 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.
╵
───
# __generated__ by Terraform
# Please review these resources and move them into your main configuration files.

# __generated__ by Terraform from "myapp-redis-data"
resource "docker_volume" "redis_data" {
  driver      = "local"
  driver_opts = {}
  name        = "myapp-redis-data"
}

How to verify: Move the generated blocks into main.tf, delete generated.tf then plan again; it should show “1 to import, 0 to change”. Common errors: generated.tf already exists → error; delete it first; to pointing to a child module → cannot generate configuration. Production use: Bring console-created resources under management, migrate state, and take over resources from other tools. Warning text depends on your Terraform version.

removed block

removed {
  from = module.staging
  lifecycle {
    destroy = false
  }
}

Lab 4: rename a module, import a manual resource, stop managing (about 8 min)

Module-level moved: stack_staging → staging
cd ~/tf-lab/myapp
sed -i 's/module "stack_staging"/module "staging"/; s/module\.stack_staging\./module.staging./' main.tf
cat >> moved.tf <<'EOF'

moved {
  from = module.stack_staging
  to   = module.staging
}
EOF
terraform plan | grep -E "^  # |Plan:"
  # module.stack_staging.docker_container.app["web1"] has moved to module.staging.docker_container.app["web1"]
  # module.stack_staging.docker_container.redis has moved to module.staging.docker_container.redis
  # module.stack_staging.docker_image.app has moved to module.staging.docker_image.app
  # module.stack_staging.docker_image.redis has moved to module.staging.docker_image.redis
  # module.stack_staging.docker_network.this has moved to module.staging.docker_network.this
Plan: 0 to add, 0 to change, 0 to destroy.
terraform apply -auto-approve
Compare: using state mv to do the same thing (preview only)
terraform state mv -dry-run module.staging module.staging2
Would move "module.staging" to "module.staging2"

The command will immediately modify remote state, while the code still has module "staging"— the next plan will plan to “destroy staging2, create staging”. This is the classic trap of imperative surgery: state and code must be changed together.

Simulate “someone created the resource manually”, and use an import block to bring it under management
docker volume create myapp-redis-data
cat > imports.tf <<'EOF'
import {
  to = docker_volume.redis_data
  id = "myapp-redis-data"
}
EOF
terraform plan -generate-config-out=generated.tf | grep -E "import|Plan:"
cat generated.tf
  # docker_volume.redis_data will be imported
Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
# __generated__ by Terraform
...
resource "docker_volume" "redis_data" {
  driver      = "local"
  driver_opts = {}
  name        = "myapp-redis-data"
}
Clean up the generated configuration, apply the import
cat >> main.tf <<'EOF'

resource "docker_volume" "redis_data" {
  name = "myapp-redis-data"     # driver defaults to local; remove attributes that equal the defaults
}
EOF
rm generated.tf
terraform plan | grep -E "import|Plan:"
terraform apply -auto-approve
terraform state list | grep volume
  # docker_volume.redis_data will be imported
Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
docker_volume.redis_data

Remove driver_opts = {} afterward; if plan shows it needs to change, the provider version handles empty maps and null differently, so keep the generated form —plan is the authority. After import, imports.tf can be deleted (an imported import block is a no-op). Mounting the volume to the redis container would cause container replacement (mounts are ForceNew); this lesson does not do it.

removed: let Terraform stop managing staging, while the containers keep running
# 1) delete module "staging" and output "staging_url" from main.tf (use an editor)
# 2) delete the stack_staging → staging moved from moved.tf (already executed, and its "to" is about to no longer exist)
# Then:
cat > removed.tf <<'EOF'
removed {
  from = module.staging
  lifecycle {
    destroy = false
  }
}
EOF
terraform plan | grep -E "no longer|Plan:"
terraform apply -auto-approve
docker ps --format '{{.Names}}' | grep myapp-stg
terraform state list | grep -c staging
 # module.staging.docker_container.app["web1"] will no longer be managed by Terraform
 # module.staging.docker_container.redis will no longer be managed by Terraform
 # module.staging.docker_image.app will no longer be managed by Terraform
 # module.staging.docker_image.redis will no longer be managed by Terraform
 # module.staging.docker_network.this will no longer be managed by Terraform
Plan: 0 to add, 0 to change, 0 to destroy.
...
myapp-stg
myapp-stg-redis
0

The staging objects are still running, but they are out of dev's state. The capstone lab will bring them back under management with import blocks in a separate root module (separate state key) — this is the full “split state” process. If you are not doing the capstone lab, clean up: docker rm -f myapp-stg myapp-stg-redis && docker network rm myapp-stg-net.

git add -A && git commit -qm "m4: moved module, import volume, removed staging"

Case 1: module v2 refactors internal resource names

Problem: The platform team wants to rename azurerm_storage_account.this in the module to .main, and split diagnostic settings into for_each. 80 callers cannot each write their own moved. Approach: Write the moved blocks inside the module, shipped with v2.0.0; the CHANGELOG notes “after upgrading, plan should show only moved”. Configuration: in the module moved { from = azurerm_storage_account.this to = azurerm_storage_account.main }. Limitation: moved blocks must be kept across several subsequent versions; deleting them too early makes callers that skip versions hit destroy-and-recreate.

Case 2: bring 200 console-created DNS records under management

Problem: Historically, all DNS records were created manually. Approach: Use a script (az network dns record-set list -o json) to generate a map, write import { for_each = local.records to = azurerm_dns_a_record.r[each.key] id = each.value.id }, and the resources also use for_each over the same map; after plan confirms “200 to import, 0 to change”, apply. Limitation:-generate-config-out Does not support for_each resources; for bulk cases, usually “write the for_each resource template first, then import”.

Case 3: split the shared network out of the application state

Problem: The VNet is in app's state, and the networking team wants to manage it independently. Approach: The networking team writes the resource + an import block in a new root module and applies; then the app root module deletes the resource code and adds removed { destroy = false }, applies; and app switches to reading the VNet through a data source. Limitation: Between the two applies the object is managed by two states at once, so changes to that resource are frozen during this period.

Common errors and fixes

Warning: Unresolved resource instance address changes ... Terraform tried to adjust resource instance addresses in the prior state based on change information recorded in the configuration, but some adjustments did not succeed.

Cause: The moved to to address already has an object in state (for example, it was previously migrated with state mv, or the new object was already created).

terraform state list | grep -E "app|stack"

Fix: Confirm which object should be kept; if necessary, use terraform state rm to remove the wrong one (back up first), then let moved take effect or delete that moved.

Error: Moved object still exists ... This statement declares a move from module.stack_staging, but that module call is still declared

Cause: The old address still exists in the configuration (you forgot to rename it, or the sed replacement failed).

Fix: Ensure from no longer exists in the configuration,to and the new address exists.

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

Cause: The ID is wrong, or the ID format is not what the provider expects.

Fix: Check the resource's “Import” section in the provider docs to confirm the ID format; for example, docker_container requires the full container ID: docker inspect -f '{{.Id}}' NAME.

Error: Target generated configuration file already exists

Fix: Delete or rename the old generated.tf before running; review the generated content and merge it into the formal files.

Error: Resource instance keys not allowed ... Resource address must be a resource (e.g. "test_instance.foo"), not a resource instance (e.g. "test_instance.foo[1]").

Cause:removed The from includes an instance key.

Fix: removed can only target a whole resource or module; when you only want to stop managing a single instance, use terraform state rm 'ADDR["key"]', and also remove that key from the for_each collection.

Command-line tasks
1. For the manually run container adminer write an import block and generate the configuration (the docker_container ID is the full container ID).
CID=$(docker inspect -f '{{.Id}}' adminer)
cat > import-adminer.tf <<EOF
import {
  to = docker_container.adminer
  id = "$CID"
}
EOF
terraform plan -generate-config-out=adminer.gen.tf
2. Before touching state, back it up, and preview the effect of renaming docker_image.app to docker_image.myapp .
terraform state pull > backup-$(date +%Y%m%d%H%M).tfstate
terraform state mv -dry-run docker_image.app docker_image.myapp
# The recommended approach is still to write a moved block: moved { from = docker_image.app  to = docker_image.myapp }
Scenario analysis
You wrote an import block to bring a production Azure storage account under management; plan shows “1 to import, 1 to change”, and the change includes public_network_access_enabled: true → false. Can you apply?

The apply will, at the same time as importing,modify the real resource: disabling public access may immediately break clients that depend on public access. First decide your intent: if it is only about bringing it under management, change the code to match the current state (true), then apply once the plan shows “1 to import, 0 to change”; disabling public access is a separate change that goes through change review and notification. Principle: bring under management and change in two separate steps.

Verified teaching videos

▶
HashiCorp Terraform Associate Certification Course - Pass the Exam! — freeCodeCamp.org
English · covers terraform import, explanation of state commands (recorded before the import/removed blocks; for block usage, this lesson takes precedence)

No verified video specifically demonstrating moved / import / removed blocks was found; a storyboard script is provided.

Official documentation

Video storyboard script (about 100 seconds)

These course materials cannot directly generate a video/MP3; a storyboard and narration script are provided for a video tool to generate.

Shot 1 · 0–25s
Visual: a line in the state ledger reads “docker_container.app → 4c1f9e”, next to a real container icon; in the code, this line is moved into a module box, and the ledger shows a red “destroy” and a green “create”.
Narration: the code moved, so the address changed. Without any hint, Terraform assumes the old one must be deleted and the new one created.
Shot 2 · 25–50s
Visual: a moved block appears; in the ledger, that line's address is erased and rewritten as the new address, and container ID 4c1f9e stays the same and glows.
Narration: the moved block rewrites the addresses in the ledger before planning begins; the object is still the same one, so the plan has zero changes.
Shot 3 · 50–75s
Visual: a volume that is not in the ledger; an import block pulls it into the ledger, and a resource code block is generated beside it.
Narration: the import block brings an existing resource under management; combined with generate-config-out it can also generate initial code, but it must be cleaned up manually.
Shot 4 · 75–100s
Visual: the removed block crosses out three staging lines in the ledger; the container on the right keeps running.
Narration: removed with destroy = false only removes the resource from the ledger; the real resource is kept. When splitting state, import into the new ledger first, then remove from the old ledger.
or score ≥ 70% on the quiz
← Module 3Module 5: validation →

Module 5 · Validation: validation, precondition / postcondition, check

30:00 – 37:00 · Write “verbal agreements” as code: invalid input fails in the first second of plan, unmet dependencies fail before anything is touched, wrong results fail right after apply, and poor runtime health gives warnings
7 minpre/postcondition 1.2 · check 1.5 · cross-variable validation 1.9★★★★☆
Learning goalsPrerequisites: m1's module interfaces; Lesson 1's expressions and functions (can,regex,alltrue) Importance:★★★★☆

What: four kinds of checks

Where it is writtenBlockWhat it can referenceWhen evaluatedFailure effect
variable Inside thevalidation { condition error_message }block for that variable; since 1.9, it can also reference other variables, locals, data sources, etc.when variable values are determined (early in plan)error, blocks
resource/data/output 's lifecycle insidepreconditionother objects, variables,self unavailableplanning (or applying) that object before; if the value is unknown, it is deferred to applyerror, blocks that object and its downstream
resource/data 's lifecycle insidepostconditionself (the object's own result) and other objectsplan / read / apply that object after; unknown values are deferred to applyerror, blocks downstream
Top levelcheck "name" { data … assert … }any object; may contain one scoped data sourceplan and apply's final stepwarning, does not block

Why: why they are needed

  • The earlier it fails, the cheaper: port 80 not allowed → fails in validation, without waiting for Docker to report “permission denied” or “port is already allocated”.
  • A module's contract: module authors express “the input range within which I can guarantee correct behavior” through validation / precondition, so callers need not read the source.
  • Continuous verification: check blocks run on every plan, and HCP Terraform can also run health assessments periodically, turning “is the infrastructure still healthy?” into a visible signal.

How: where it sits in plan/apply

  1. Load configuration, determine input variables → evaluate one by one validation. When a condition depends on unknown values (for example, referencing an attribute of a resource not yet created), it is deferred to apply.
  2. Walk the dependency graph: when it is a resource's turn, first evaluate its precondition, then call the provider PlanResourceChange, and after getting the planned values, evaluate postcondition (self refers to the planned values; if a key attribute is unknown in the plan, postcondition is deferred until ApplyResourceChange returns.
  3. The precondition of an output (output) is checked before the output is evaluated; it is often used to ensure “only valid values are exposed to callers”.
  4. After all resources are processed, check blocks are evaluated: first read the scoped data source (its errors are downgraded to warnings), then evaluate the assert.

Common syntax for condition expressions

  • Regex: can(regex("^[a-z][a-z0-9-]{1,20}$", var.name_prefix)) (regex a mismatch raises an error,can turn it into false).
  • Set: alltrue([for k, v in var.app_instances : v.port >= 1024 && v.port <= 65535]).
  • Uniqueness: length(distinct([for v in var.app_instances : v.port])) == length(var.app_instances).
  • Enumeration: contains(["dev", "staging", "prod"], var.environment).
  • error_message can use interpolation to show the current value (see the official documentation for your version for reference rules), and clearly state the expected value and the fix.

When: which one to choose

What to checkRecommended
input format, range, enumeration, combination rulesvalidation
dependent objects meet an assumption (AMI architecture, image source, subnet size)precondition
results returned by the provider meet expectations (container connected to the correct network, certificate not expired)postcondition
health status, external endpoints, reminders that should not block deploymentcheck
organization-level policies (tags, regions, SKU allowlists)Policy as Code (Trivy/Checkov m7, Terraform Policy / Sentinel / OPA Lesson 5)

Comparison with similar technologies

TerraformBicepPulumiK8s
Input validationvalidation@allowed,@minValue etc. decoratorshost-language codeCRD OpenAPI schema / CEL
runtime assertionspre/postconditionNo direct equivalentCode + Policy PackValidatingAdmissionPolicy
Continuous health checkscheck blockNoneNoneProbes
Common misconceptions① “A failed check makes CI fail” — no; a check only produces a warning. To block, use postcondition or parse terraform show -json 's checks field. ② “validation can only check the current variable” — since 1.9 it can reference other variables and objects, but referencing unknown values defers the validation to apply. ③ “When a precondition fails, other resources are not created either” — only that object and those depending on it are blocked; unrelated branches of the graph still run. ④ “Using can() is the safest” —can swallows real problems such as typos; only use it for functions that error on “invalid values”.

Timeline diagram: trigger points of the four checks during apply

Input variablesvalidation (error) before planning resource Xprecondition (error) PlanResourceChangeprovider gRPC planned values / resultpostcondition (error) final stepcheck (warning) value unknown at plan time (such as a new image's repo_digest) → condition deferred to apply precondition is evaluated before ApplyResourceChange, postcondition is evaluated again after it for each resource in the graph, repeat “pre → provider → post”; they are independent and run in parallel
Figure 5-1: the further left the failure, the cheaper; only check does not block the operation

Decision diagram: which kind of check should this rule be written as?

Rule to check Only about inputs? → validation About assumptions on dependent objects? → precondition About the object's own result? → postcondition Should a failure block deployment?No (just want to know, e.g. an external endpoint is temporarily unavailable) → checkOrganization-wide, consistent across repos → policy tool (m7 / Lesson 5)
Figure 5-2: a simple decision for choosing the validation type

Interactive demo: at which gate is a defect caught?

Choose a defect and click “Run terraform apply”. The animation steps through the stages in real order, stops at the interception point, and shows Terraform's output.

Syntax and commands

Syntax / commandPurposeNotes
validation { condition = … error_message = "…" }Variable validationA variable can have multiple validation blocks
lifecycle { precondition { … } }Preconditionresource, data, output all allowed
lifecycle { postcondition { … self … } }Postconditionresource, data
check "x" { data "http" "h" { … } assert { … } }Health checkScoped data source is only visible inside check
terraform plan -var 'x=…'Quickly validate validationNo need to apply
terraform show -json tfplan | jq '.checks'Read check results in CIstatus: pass / fail / error / unknown
variable "environment" {
  description = "Environment name"
  type        = string
  default     = "dev"
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging or prod; the current value is \"${var.environment}\"."
  }
}

variable "name_prefix" {
  description = "Prefix for all Docker object names"
  type        = string
  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{1,20}$", var.name_prefix))
    error_message = "name_prefix may only contain lowercase letters, digits and hyphens, must start with a letter, and be 2–21 characters long."
  }
}

variable "app_image" {
  type    = string
  default = "myapp:1.0"
  validation {
    condition     = can(regex(":[^:/]+$", var.app_image)) && !endswith(var.app_image, ":latest")
    error_message = "app_image must include an explicit tag and must not be latest, e.g. myapp:1.0."
  }
}

variable "app_instances" {
  type = map(object({
    port = number
    name = optional(string)
  }))
  default = { web1 = { port = 8080 } }

  validation {
    condition     = alltrue([for k, v in var.app_instances : v.port >= 1024 && v.port <= 65535])
    error_message = "All ports must be between 1024 and 65535 (ports that non-root users can bind)."
  }
  validation {
    condition     = length(distinct([for v in var.app_instances : v.port])) == length(var.app_instances)
    error_message = "Ports in app_instances must be unique."
  }
  validation {   # 1.9+: references another variable
    condition     = var.environment != "prod" || length(var.app_instances) >= 2
    error_message = "The prod environment needs at least 2 application instances."
  }
}
resource "docker_container" "app" {
  for_each = var.app_instances
  # ... (same as m3)

  lifecycle {
    precondition {
      condition     = var.environment != "prod" || docker_image.app.repo_digest != ""
      error_message = "prod may only use images pulled from a registry and pinned by digest; the locally built ${var.app_image} has no repo_digest."
    }
    postcondition {
      condition     = contains([for n in self.network_data : n.network_name], docker_network.this.name)
      error_message = "Container ${self.name} is not connected to network ${docker_network.this.name}."
    }
  }
}
check "app_health" {
  data "http" "healthz" {
    url = "http://localhost:${values(var.app_instances)[0].port}/healthz"
    retry {
      attempts     = 5
      min_delay_ms = 1000
    }
    depends_on = [docker_container.app]
  }

  assert {
    condition     = data.http.healthz.status_code == 200
    error_message = "${data.http.healthz.url} returned ${data.http.healthz.status_code}; the application may be unhealthy."
  }
}
    http = {
      source  = "hashicorp/http"
      version = ">= 3.4, < 4.0"     # latest at verification time is 3.6.3
    }

Notes:repo_digest,network_data are docker_image/docker_container computed attributes; the names follow the provider 4.x docs; a new image's repo_digest is unknown at plan time, so the precondition is deferred to apply. The scoped data source in a check block reads only one endpoint (the official documentation lists only for nested data blocks depends_on and provider two meta-arguments).

Lab 5: add a contract to the module and trigger each check one by one (about 7 min)

Write the validations: following the “Commands” page, modify modules/stack/variables.tf,main.tf, add checks.tf, and in versions.tf add the http provider, then:
cd ~/tf-lab/myapp
terraform init                    # install the newly added hashicorp/http (and update the lock file)
terraform validate && terraform plan | tail -3
Success! The configuration is valid.
...
No changes. Your infrastructure matches the configuration.

If a check warning appears at the end of plan, it means /healthz is temporarily unavailable; first use curl to investigate.

Trigger validation (no apply needed)
# Temporarily change web1's port in the root module to 80, or use a method other than the console:
sed -i 's/web1 = { port = 8080, name = "myapp" }/web1 = { port = 80, name = "myapp" }/' main.tf
terraform plan 2>&1 | grep -A3 "Error:"
git checkout main.tf
│ Error: Invalid value for variable
│
│   on main.tf line 12, in module "stack":
│   12:   app_instances = {
│     ├────────────────
│     │ var.app_instances is map of object with 2 elements
│
│ All ports must be between 1024 and 65535 (ports non-root users can bind).
Trigger cross-variable validation and precondition: in the root module module "stack" , temporarily add environment = "prod"
terraform plan 2>&1 | grep -E "Error|prod" | head -4
│ Error: Resource precondition failed
│ prod may only use images pulled from a registry and pinned by digest; the locally built myapp:1.0 has no repo_digest.

The current stack has 2 instances (web1, web3), which satisfies “prod needs at least 2 instances”; delete web3 and plan again, and you will first see the validation error. After testing, revert: git checkout main.tf.

Trigger check warning (non-blocking)
docker stop myapp
terraform plan 2>&1 | grep -A4 "Warning: Check block assertion failed"
docker start myapp
│ Warning: Check block assertion failed
│
│   on modules/stack/checks.tf line 13, in check "app_health":
│   13:     condition     = data.http.healthz.status_code == 200
│
│ http://localhost:8080/healthz returned 0; the application may be unhealthy.

When the connection is refused, the data source itself errors, and Terraform downgrades it to a warning (the wording may be “Error making request …”, depending on the http provider version). Plan still finishes successfully. Note restart = "unless-stopped" will not automatically start a container that was manually stopped, so you must manually docker start; also, plan may show a container update is needed (runtime-state drift), which is exactly the signal m8's drift detection should watch for.

Commit: git add -A && git commit -qm "m5: validations, conditions, health check"

Case 1: someone changed prod's replica count to 1

Problem: To save money, someone changed prod's instance_count to 1 in the PR, and the review missed it. Approach: Add cross-variable validation (1.9+) in the module: var.environment != "prod" || var.instance_count >= 2. Limitation: validation only prevents “accidents”; anyone with permission to change the module can still change the rule — put organization-level rules in a policy tool.

Case 2: AMI architecture does not match the instance type

Problem: The data source found the latest AMI is arm64, but the instance type is m6i (x86); during apply the EC2 API errored, and half the stack had already been created. Approach: In aws_instance write a precondition: data.aws_ami.app.architecture == "x86_64"; it fails at the plan stage. Limitation: If a data source depends on unknown values, the check is deferred to apply.

Case 3: certificate expiry reminder

Problem: The managed certificate is renewed by another team, and nobody notices before it expires. Approach:check "cert_expiry" Use a data source to read the certificate and assert that it expires more than 30 days from now; HCP Terraform's health assessments run periodically and send notifications. Limitation: A check only warns and does not block; if it must block the release, use a postcondition instead.

Common errors and fixes

Error: Invalid value for variable ... all ports must be between 1024–65535

Cause: The input does not satisfy the validation. Fix: Change the input as described in error_message. Module authors should make sure the message states “what is expected and how to fix it”.

Error: Invalid reference in variable validation ... The condition for variable "x" can only refer to the variable itself, using var.x.

Cause: The Terraform version is older than 1.9, so validation cannot reference other variables.

terraform version

Fix: Upgrade to 1.9+ and declare it in required_version (m8), or rewrite the rule as a precondition.

Error: Resource postcondition failed ... container myapp is not connected to network myapp-net

Cause: The provider returned a result that differs from what was expected (usually the network was disconnected manually or renamed). Diagnosis:docker inspect myapp -f '{{json .NetworkSettings.Networks}}'. Fix: Reconnect it, or let Terraform replace the container (terraform apply -replace='module.stack.docker_container.app["web1"]').

Warning: Check block assertion failed ... returned 0 / Error making request: connection refused

Cause: The application has not started or is not ready yet. Fix: Check the container logs docker logs myapp; on first creation, increase retry.attempts. Note: This is a warning: CI will not fail, so set up a separate alert.

Error: Invalid function argument ... Invalid value for "str" parameter: argument must not be null.

Cause: A condition calls a string function on an optional attribute (optional() which is null when unset). Fix: First check for null: v.name == null || can(regex("…", v.name)), or use coalesce to supply a default.

Command-line exercises
1. After saving the plan, use jq to list the name and status of every check.
terraform plan -out=tfplan
terraform show -json tfplan | jq -r '.checks[]? | "\(.address.to_display) \(.status)"'
2. Use console to verify the results of the image-name validation expression for myapp:latest and myapp:1.0 the results.
echo 'can(regex(":[^:/]+$", "myapp:latest")) && !endswith("myapp:latest", ":latest")' | terraform console
echo 'can(regex(":[^:/]+$", "myapp:1.0")) && !endswith("myapp:1.0", ":latest")' | terraform console
# Output: false / true
Scenario analysis
The team wants “the database SKU must be one of an allowed list, and prod must have geo-redundant backup enabled”, and also wants “after each deployment, check that the database endpoint is reachable; if it is not, warn but do not roll back”. How would you implement each?

The SKU allow-list and “prod must have geo-redundant backup enabled” are input rules → variable validation (the latter references the environment variable and needs 1.9+); if it is a company-wide requirement, repeat it in a policy tool. Endpoint reachability → a check block (scoped data source + assert); failures only produce warnings, which satisfies “warn but do not roll back”; if notifications are needed, parse the result in CI checks or use HCP Terraform health assessment.

Verified instructional video

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · The variables and validation sections can serve as supplementary material; the check block and cross-variable validation came after this video, so follow this lesson.

No verified video dedicated to precondition / postcondition / check was found; a storyboard script is provided instead.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: a left-to-right pipeline with four gates in order: validation, precondition, postcondition, check.
Narration: Terraform has four gates; the earlier a problem is caught, the cheaper it is.
Shot 2 · 20–45s
Visual: a package labelled “port 80” is bounced back at the first gate; the screen shows an error message.
Narration: variable validation runs at the very start of the plan, and a good error message tells the caller what to change.
Shot 3 · 45–65s
Visual: the resource block has a pre-check light on its left and a post-check light on its right, with the provider call in the middle.
Narration: a precondition checks dependencies before the provider is called; a postcondition checks the resource itself after the result comes back.
Shot 4 · 65–80s
Visual: at the end of the pipeline, the check gate lights a yellow warning, but the package keeps moving.
Narration: the check block runs last; a failure is only a warning and does not block deployment, which makes it suitable for health checks.
or score ≥ 70% on the quiz
← Module 4Module 6: terraform test and mock →

Module 6 · terraform test and mock

37:00 – 45:00 · Write tests in HCL: command = plan + mock for unit tests that run in seconds,command = apply real Docker for integration tests, destroyed automatically when the test finishes
8 minutestest 1.6 · mock 1.7 · junit GA 1.11override_during 1.11★★★★☆
Learning objectivesPrerequisites: validation and precondition from m5 (they are the best things to test). Importance:★★★★☆

What: the terraform test framework

  • Test files: extension .tftest.hcl or .tftest.json, placed in the root directory of the module under test or tests/ directory (-test-directory default tests). Run terraform test, so the object under test is the configuration in that directory.
  • Top-level blocks: test (0–1, configured like parallel),run (one or more),variables (0–1),provider,mock_provider,override_resource/override_data/override_module.
  • run block fields: command (default apply, or plan),plan_options (mode/refresh/replace/target),variables,module (supports only source,version, used to load helper modules),providers,assert,expect_failures,state_key,parallel.
  • Assertions: assert { condition error_message } can reference the module under test's resources, data sources, variables, and outputs (output.app_urls) and the outputs of earlier run blocks (run.deploy.app_urls).
  • expect_failures: lists the checkable objects expected to fail (variables, resources, outputs, check blocks). The test passes only if that object's validation actually fails; this is the standard way to test validation and precondition.

Why: why IaC needs tests too

  • Modules are code reused by many people: changing one default value or one for expression affects every caller. Tests are the safety net for module refactoring (m4).
  • Validation can itself be wrong: validation a reversed condition rejects all inputs or accepts all of them; only expect_failures tests can catch it.
  • Plan-level unit tests are very fast: combined with mock, they need no cloud account, cost nothing, and finish in seconds, so they suit every commit; integration tests with a real apply run before merging or overnight.

How: execution flow

  1. Test files are processed in alphabetical order; run blocks inside a file run by default in order (unless parallel = true run blocks with non-conflicting state can run in parallel).
  2. For each run block: merge variables (command line / tfvars → file variables → run-level variables, the latter taking precedence), choose the provider (real or mock), run plan or apply, then evaluate assert and expect_failures.
  3. state: run blocks in the same file that target the main configuration share one in-memory state (each later run builds on the previous result); a run block that loads module { source } has its own independent state; state_key can explicitly choose sharing or isolation.
  4. After all run blocks in the file finish, Terraform, in reverse order of creation,destroys all resources created by that file. If an integration test fails midway, Terraform still tries to clean up; if cleanup fails, it prints the leftover resources, which must be removed manually.

How mocks work

  • mock_provider "docker" {}: it uses the same provider schema to generate a “fake provider” that makes no real API calls; required attributes must still be given in the configuration,computed attributes are generated automatically: numbers 0, booleans false, strings a random 8-character alphanumeric string, lists / sets / maps empty, objects generated recursively.
  • mock_resource "docker_container" { defaults = { … } }: set a value for computed attributes of a resource type (for example, to make network_data have content, so the postcondition passes).
  • override_resource { target = … values = { … } }: override a specific resource’s values (works with the real or mock provider); override_data likewise,override_module { target outputs } replace the outputs of an entire module call directly.
  • By default, generated values appear only at apply time (the plan still shows them as known after apply); override_during = plan (1.11+) makes values known at plan time, which suits command = plan plan-level unit tests.

When: test layers

LayerApproachSpeed / costWhen to run
Static checksfmt / validate / tflint (m7)millisecondsEvery save / commit (pre-commit)
Unit testscommand = plan + mock_providerseconds, zero costEvery push / PR
Contract testsexpect_failures Cover every validation / preconditionsecondsEvery PR
Integration testscommand = apply + real provider + helper-module verificationMinutes-level, with cost (in the cloud)Before merging, overnight, and before publishing a new module version

Comparison with similar tools

terraform testTerratest (Go)Pulumi unit testskitchen-terraform
LanguageHCLGoHost languageRuby (no longer active)
mockBuilt-in mock_provider / overrideMust be implemented yourselfmocks interfaceNone
Best forModule contracts and most integration testsComplex end-to-end validation (SSH, HTTP, retry logic)Pulumi projects—
Common misconceptions① “terraform test uses my remote backend”: no. Tests use temporary in-memory state and never read or write the backend's state. But integration tests do create real resources, so use names and ports that do not conflict (this lab uses itest prefix and 18xxx ports). ② “a mock proves the configuration works in the cloud”: no. A mock only checks Terraform logic (expressions, conditions, naming) and does not verify whether the API accepts these values. ③ “command = plan test can assert any attribute”: computed attributes are unknown in the plan, so asserting on them fails unless you use a mock plus override_during = plan.

Architecture diagram: test files, the module under test, and the provider

modules/stack/tests/ unit.tftest.hclmock_provider "docker" / "http"run × 6 (command = plan / apply)expect_failures covers validation integration.tftest.hclreal providerrun "deploy" → run "healthz"module { source = "./tests/http" } module under testmodules/stackvariables + validationresources + conditionscheck "app_health"outputsin-memory state (does not touch the backend) mock providersame schema, no API callscomputed attributes: 0 / false / 8-character random stringdefaults / override coverage real kreuzwerker/dockerDocker Engine APIitest-web1 :18090destroyed automatically when the test ends
Figure 6-1: the same module; unit tests use the mock, integration tests use the real provider

Flowchart: lifecycle of one test file

Load filevariables / providers run 1plan|apply → assert run 2inherits run 1's state run Ncan reference run.x.output teardowndestroy in reverse order pass/fail If a run fails, later runs still attempt to execute by default (those that depend on the failed run's output are skipped), and cleanup always runs at the end
Figure 6-2: run blocks execute in sequence like a “script”; cleanup happens at the end of the file

Test-runner simulation: runs run blocks one by one

Tick “Introduce a bug” to simulate someone changing the default naming to ${name_prefix}_${key} (underscores), and watch which test fails and why.

Core commands and options

CommandPurposeKey options
terraform testRun the current directory and tests/ all tests underrequires running terraform init
terraform test -filter=tests/unit.tftest.hclRun only the specified filecan be repeated
terraform test -verbosePrint the plan / state of each runfor debugging assertions
terraform test -test-directory=DIRSpecify the test directorydefault tests
terraform test -junit-xml=report.xmlOutput a JUnit report (1.11 GA)Show test results in CI
terraform test -var 'k=v' / -var-filePass variableslower precedence than variables in the test file
mock_provider "docker" {
  mock_resource "docker_container" {
    defaults = {
      network_data = [{ network_name = "unit-net" }]   # lets the postcondition pass under mock apply
    }
  }
}

mock_provider "http" {
  mock_data "http" {
    defaults = { status_code = 200 }                  # check block raises no warning
  }
}

variables {
  name_prefix = "unit"
  app_instances = {
    web1 = { port = 18080 }
    api  = { port = 18081, name = "custom-api" }
  }
}

run "names_follow_prefix" {
  command = plan

  assert {
    condition     = docker_container.app["web1"].name == "unit-web1"
    error_message = "Default container name should be <name_prefix>-<key>, but is ${docker_container.app["web1"].name}"
  }
  assert {
    condition     = docker_container.app["api"].name == "custom-api"
    error_message = "An explicit name should override the default naming"
  }
  assert {
    condition     = docker_network.this.name == "unit-net" && docker_container.redis.name == "unit-redis"
    error_message = "Network and redis names do not follow the convention"
  }
  assert {
    condition     = output.app_urls["web1"] == "http://localhost:18080"
    error_message = "app_urls output is incorrect"
  }
}

run "rejects_privileged_port" {
  command   = plan
  variables {
    app_instances = { web1 = { port = 80 } }
  }
  expect_failures = [var.app_instances]
}

run "rejects_duplicate_ports" {
  command   = plan
  variables {
    app_instances = { a = { port = 18080 }, b = { port = 18080 } }
  }
  expect_failures = [var.app_instances]
}

run "rejects_latest_tag" {
  command   = plan
  variables {
    app_image = "myapp:latest"
  }
  expect_failures = [var.app_image]
}

run "prod_requires_registry_image" {
  command = plan
  variables {
    environment = "prod"
  }
  override_resource {
    target          = docker_image.app
    values          = { repo_digest = "" }
    override_during = plan          # 1.11+: use the override value already at the plan stage
  }
  expect_failures = [docker_container.app]
}

run "mock_apply_outputs" {
  command = apply                   # mock apply: does not connect to Docker
  assert {
    condition     = length(output.container_names) == 3
    error_message = "There should be 2 app containers + 1 redis container"
  }
}

Note: error_message in <name_prefix> is just plain text. prod_requires_registry_image has 2 instances, which satisfies the “prod needs at least 2 instances” validation, so only the precondition can fail.

variables {
  name_prefix   = "itest"
  app_instances = { web1 = { port = 18090 } }
}

run "deploy" {
  command = apply
  assert {
    condition     = contains([for n in docker_container.app["web1"].network_data : n.network_name], "itest-net")
    error_message = "Container is not connected to itest-net"
  }
}

run "healthz" {
  module {
    source = "./tests/http"
  }
  variables {
    url = "${run.deploy.app_urls["web1"]}/healthz"
  }
  assert {
    condition     = output.status_code == 200
    error_message = "Health check failed: ${output.status_code}"
  }
}
terraform {
  required_providers {
    http = { source = "hashicorp/http" }
  }
}

variable "url" {
  type = string
}

data "http" "this" {
  url = var.url
  retry {
    attempts     = 10
    min_delay_ms = 1000
  }
}

output "status_code" {
  value = data.http.this.status_code
}

Lab 6: write unit and integration tests for modules/stack (about 8 minutes)

Create the test files: copy the three files from the “Commands” tab into modules/stack/tests/
cd ~/tf-lab/myapp/modules/stack
mkdir -p tests/http
# Write tests/unit.tftest.hcl, tests/integration.tftest.hcl, and tests/http/main.tf
terraform init          # initialize in the module directory (the tests need the provider)
ls tests
http  integration.tftest.hcl  unit.tftest.hcl

In the module directory init will create modules/stack/.terraform/ and a lock file: .terraform/ Add .gitignore; the .terraform.lock.hcl is for testing only; the team can agree whether to commit or ignore it.

Run unit tests only (no Docker needed)
terraform test -filter=tests/unit.tftest.hcl
tests/unit.tftest.hcl... in progress
  run "names_follow_prefix"... pass
  run "rejects_privileged_port"... pass
  run "rejects_duplicate_ports"... pass
  run "rejects_latest_tag"... pass
  run "prod_requires_registry_image"... pass
  run "mock_apply_outputs"... pass
tests/unit.tftest.hcl... tearing down
tests/unit.tftest.hcl... pass

Success! 6 passed, 0 failed.

You can stop Docker and run again to verify that it truly does not depend on the daemon. If prod_requires_registry_image reports override_during is not supported, which means Terraform is below 1.11; change this run to command = apply and remove override_during.

Verify that the tests catch bugs: temporarily change main.tf the default naming in
sed -i 's/"${var.name_prefix}-${each.key}"/"${var.name_prefix}_${each.key}"/' main.tf
terraform test -filter=tests/unit.tftest.hcl 2>&1 | grep -E "run |Error|Default container|Failure"
git checkout main.tf
  run "names_follow_prefix"... fail
│ Error: Test assertion failed
│ Default container name should be <name_prefix>-<key>, but is unit_web1
Failure! 5 passed, 1 failed.
Run integration tests (real containers)
terraform test -filter=tests/integration.tftest.hcl
docker ps -a --format '{{.Names}}' | grep -c itest || true
tests/integration.tftest.hcl... in progress
  run "deploy"... pass
  run "healthz"... pass
tests/integration.tftest.hcl... tearing down
tests/integration.tftest.hcl... pass

Success! 2 passed, 0 failed.
0

The last line, 0, shows the itest container was destroyed after the test. Integration tests require the local machine to have the myapp:1.0 image, and port 18090 must be free.

Generate a JUnit report and commit
terraform test -junit-xml=test-report.xml >/dev/null; head -3 test-report.xml
cd ~/tf-lab/myapp && printf 'modules/stack/.terraform/\ntest-report.xml\n' >> .gitignore
git add -A && git commit -qm "m6: terraform tests (unit + integration)"
<?xml version="1.0" encoding="UTF-8"?><testsuites>
  <testsuite name="tests/integration.tftest.hcl" tests="2" skipped="0" failures="0" errors="0">
    <testcase name="deploy" classname="tests/integration.tftest.hcl" time="2.41" timestamp="2026-11-15T11:02:13Z"></testcase>

Case 1: every validation in the module has an expect_failures test

Problem: The platform team’s storage module had 14 validations. A refactor reversed the condition for “block public network access”, so every caller could enable public access, and a security scan caught it only three weeks later. Approach: Agree that “each validation / precondition has at least one passing case and one expect_failures case”, and add a checklist item to the PR template. Limitation: Tests only cover rules that are written down; organisation-wide rules still need a policy tool.

Case 2: cost and cleanup of cloud integration tests

Problem: Overnight integration tests create AKS in Azure; in one run the runner crashed midway, and the leftover resources kept incurring costs. Approach: Tag all test resources with expires-on a tag and a separate resource-group prefix; a scheduled daily job cleans up expired resource groups; tests use a dedicated subscription and budget alerts. Limitation: terraform test’s teardown depends on the process exiting normally.

Case 3: isolate a slow dependency with override_module

Problem: The application module depends on the network module, so every unit test has to plan the entire network. Approach:override_module { target = module.network outputs = { subnet_ids = { app = "subnet-mock" } } }, so the application module’s unit tests only check its own logic. Limitation: The mock’s output shape must match the real module; update it at the same time when the network module changes its interface.

Common errors and fixes

Error: Test assertion failed ... Default container name should be <name_prefix>-<key>, but is unit_web1

Cause: The logic under test does not match the assertion: either the code has a bug, or the requirement changed and the test needs updating. Diagnosis:terraform test -verbose -filter=… Inspect the planned values.

Error: Unknown condition value ... Condition expression could not be evaluated at this time. This means you have executed a `run` block with `command = plan` and one of the values your condition depended on is not known until after the plan has been applied.

Cause: A plan-level test asserted a computed attribute. Fix: Change it to command = apply (combined with mock), or use override_resource + override_during = plan to make it known.

Error: Missing expected failure ... The checkable object, var.app_instances, was expected to report an error but did not.

Cause: The validation did not reject the input as expected (the condition is reversed, or the input is actually valid). Fix: Check the logic of the condition; this is exactly the bug the test is meant to catch.

Error: Inconsistent dependency lock file ... provider registry.terraform.io/hashicorp/http: required by this configuration but no version is selected

Cause: A helper module in the test directory needs a new provider, but init was not rerun. Fix: In the directory where the tests run, run terraform init (this also collects the provider requirements of helper modules).

Terraform left the following resources in state after executing tests/integration.tftest.hcl, and they need to be cleaned up manually: docker_container.app["web1"]

Cause: Teardown failed (the daemon disconnected, or a permissions problem). Fix: Delete the leftover resources manually as the output indicates: docker rm -f itest-web1 itest-redis && docker network rm itest-net; in the cloud, clean up by tag.

Command-line exercises
1. Run only the unit test file and output the detailed plan, for debugging a failing assertion.
terraform test -filter=tests/unit.tftest.hcl -verbose
2. Write a run block that verifies environment = "qa" is rejected.
run "rejects_unknown_environment" {
  command = plan
  variables {
    environment = "qa"
  }
  expect_failures = [var.environment]
}
Scenario analysis
The team wants module tests to run on every PR, but integration tests create a VNet + AKS in Azure, take 15 minutes, and cost about $2 each time. How would you design the tests and the pipeline?

Layer it: on PRs, run fmt / validate / tflint / scanning, plus mock unit tests and expect_failures contract tests (seconds, zero cost); run integration tests only before merging to main (for labelled PRs or the merge queue), on a nightly schedule, and before publishing a new module version; integration tests use a dedicated subscription, a unique prefix, budget alerts, and scheduled cleanup; publish the test results with -junit-xml JUnit reporting. For slow dependency modules, use override_module in unit tests to replace them.

Verified instructional video

No verified video specifically explaining terraform test and mock_provider videos was found (candidates on HashiCorp’s official channel were checked, but the specific video IDs could not be confirmed via oEmbed). Below are verified videos that can serve as background, plus a storyboard script.

▶
Introduction to HashiCorp Terraform with Armon Dadgar — HashiCorp, an IBM Company
English · Video by a HashiCorp co-founder explaining the Terraform workflow (recorded earlier, does not cover the test framework)

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: a .tftest.hcl file expands into multiple run cards arranged in a column.
Narration: terraform test writes tests in HCL; each run block is one plan or apply, and later runs build on earlier results.
Shot 2 · 20–45s
Visual: the real Docker whale icon is replaced by a dashed-outline “fake provider”, and random strings appear in the attribute panel.
Narration: the mock provider uses the same schema but calls no APIs; computed attributes are generated automatically, so unit tests finish in seconds.
Shot 3 · 45–70s
Visual: input “port 80”; validation lights red, yet the test card shows a green pass, labelled expect failures.
Narration: expect failures tests the validation itself. The test passes only when the validation fails as expected.
Shot 4 · 70–90s
Visual: the integration test creates a real container, the health check returns 200, and finally the containers disappear one by one.
Narration: the integration test creates real resources and destroys them automatically in reverse order when the test ends.
or score ≥ 70% on the quiz
← Module 5Module 7: static checks and security scanning →

Module 7 · static checks and security scanning

45:00 – 52:00 · Find problems without running anything; do not leave them until plan. pre-commit blocks them locally, and CI blocks them again
7 minutestflint v0.66.0 · Trivy v0.76.2 · Checkov 3.4.5pre-commit-terraform v1.109.5★★★★☆
Learning objectivesPrerequisites: Code structure from m1–m6. Importance:★★★★☆

What: five checkpoints

ToolWhat it checksRequiresTypical findings
terraform fmt -check -recursiveCanonical formatting (indentation, alignment, quotes)Reads files onlyMeaningless diffs caused by inconsistent formatting
terraform validateSyntax, references, types, required argumentsinit (can -backend=false) fetch the provider schemaReferences to nonexistent variables, misspelled argument names
tflintPluggable rules: Terraform language best practices (terraform ruleset), cloud-provider-specific rules (aws / azurerm / google ruleset)tflint --init Download pluginsUnused variables, undeclared types, unpinned module versions, invalid instance types
Trivy (trivy config)IaC security misconfigurations (tfsec has been merged into Trivy)Read-only code; optionally reads tfvarsUnencrypted storage, public access, overly broad security groups
CheckovIaC security and compliance policies (thousands of built-in rules, supports graph rules)Python package or containerCKV_AWS_* and CKV_AZURE_* rules

Why: why so many tools

  • validate only guarantees “it parses”: it does not know t3.superlarge is not a valid instance type (tflint-ruleset-aws knows), and it does not know that a storage account allowing public network access is a risk (Trivy / Checkov know).
  • Shift left: failing with pre-commit on the developer's machine is faster than failing in the PR, cheaper than failing at apply, and more graceful than being found in an audit.
  • Focus reviews: anything a machine can check need not be reviewed by a human; reviewers focus on design and plan results.

How: how each tool works

  • tflint: parses HCL (without calling the provider) and statically evaluates expressions; plugins talk to tflint over gRPC. .tflint.hcl declares plugins and rules in call_module_type ; controls whether module calls are checked (by default only local modules are checked). v0.66.0 (2026-11-08) added support for Terraform 1.17.
  • Trivy: parses the Terraform code into an internal model (evaluating variable defaults and expanding local modules), then uses Rego to check rules against resource attributes. trivy config . Scans directories,--severity HIGH,CRITICAL filters by severity,--exit-code 1 to make CI fail; ignore issues with code comments #trivy:ignore:<ID> or .trivyignore.
  • Checkov: parses HCL to build a resource graph and runs Python / YAML policies; --framework terraform,--check/--skip-check select rules, suppress inline #checkov:skip=CKV_AWS_18:reason. You can also scan plan JSON (terraform show -json), so you can see the computed values.
  • pre-commit: on git commit runs a set of hooks on changed files; antonbabenko/pre-commit-terraform provides terraform_fmt,terraform_validate,terraform_tflint,terraform_trivy,terraform_checkov,terraform_docs and other hooks. In CI, use pre-commit run --all-files to run the same checks, keeping local and CI consistent.

About the Docker provider in this course

Trivy and Checkov’s built-in rules mainly cover AWS / Azure / GCP / Kubernetes and so on, and have essentially no rules for kreuzwerker/docker resources; scanning the myapp stack gives “0 issues”, which does not mean it is secure. The lab therefore adds an extra scan-only, never-deployed AWS S3 example directory that demonstrates what scan results look like; the cloud code in lessons 3 and 4 will use these scans for real.

When: where to run

StageRunFailure policy
Editorterraform-ls / IDE plugins (fmt on save, validate)Hint
git commitpre-commit: fmt, validate, tflint, trivy (HIGH+)Blocks the commit (can --no-verify be skipped, but CI will block again)
PR / CIpre-commit run --all-files + terraform test + Checkov (SARIF uploaded to code scanning)Blocks the merge
After planScan plan JSON (Checkov / Trivy), Terraform Policy / OPA / Sentinel (lesson 5)Blocks apply

Comparison with similar tools

TrivyCheckovtflintKICS / Terrascan
PositioningComprehensive scanner (images, dependencies, IaC, secrets)IaC policy as codeLinterIaC scanning (Terrascan is no longer maintained; check the official repository)
Rule languageRegoPython / YAMLGo pluginRego
Link to the Docker lessonAlready used when scanning images———
Common misconceptions① “0 scan issues = secure”: rules only cover known patterns, and may not cover the provider you use at all. ② “Block every MEDIUM/LOW”: noise leads the team to add ignores by reflex; block HIGH/CRITICAL first, send the rest to a backlog, and write a reason and expiry date for every ignore. ③ “terraform validate needs cloud access”: no. After terraform init -backend=false that, it runs offline (the provider must already be downloaded). ④ “tflint includes AWS / Azure rules”: no, the matching ruleset plugin must be enabled separately.

Flowchart: quality gates locally and in CI

Local: git commit → pre-commit terraform_fmtauto-fix formatting terraform_validateinit -backend=false terraform_tflintrecommended preset terraform_trivyHIGH,CRITICAL Commit succeeds → git pushAny hook failure blocks CI: Pull Request pre-commit run -aSame checks as local terraform testmock unit tests checkovSARIF → code scanning plan + scan planLesson 5 Human reviewFocus on design and plan Local hooks can be skipped with --no-verify, so CI must repeat the same checks
Figure 7-1: the same .pre-commit-config.yaml drives local and CI

Coverage map: which tool catches which kind of problem

ProblemfmtvalidatetflintTrivy/Checkovtest Inconsistent indentation● Reference to a nonexistent variable●● Unused variable / undeclared type● S3 bucket does not block public access● Wrong default naming logic / reversed validation● Port conflict, missing image (at runtime)→ plan/apply, integration tests, check blocks
Figure 7-2: the tools complement rather than replace one another

Interactive demo: which checkpoint catches the defect?

Tick the defects to “commit”, then run git commit. The animation runs each hook in turn, showing each tool’s real output format.

Core commands and options

CommandPurposeKey options
terraform fmt -check -recursive -diffCheck formatting (CI)Drop -check and it auto-fixes
terraform init -backend=false && terraform validateOffline validation-json for easy tool parsing
tflint --initDownload .tflint.hcl plugins declared inRecommended setting GITHUB_TOKEN to avoid API rate limits
tflint --recursiveRecursively check all directories--format compact|json|sarif,--minimum-failure-severity
trivy config .IaC configuration scan--severity HIGH,CRITICAL,--exit-code 1,--tf-vars
checkov -d . --framework terraformpolicy scan--compact,--quiet,-o sarif,--skip-check
pre-commit run --all-filesrun hooks on all filespre-commit install Install git hooks; pre-commit autoupdate Update the rev

install (version verified in 2026-11)

# tflint v0.66.0 (the official install script installs the latest version; to pin a version, download the release asset directly)
curl -sLo /tmp/tflint.zip https://github.com/terraform-linters/tflint/releases/download/v0.66.0/tflint_linux_amd64.zip
sudo unzip -o /tmp/tflint.zip -d /usr/local/bin && tflint --version

# Trivy v0.76.2 and Checkov 3.4.5: run them in containers, no installation needed
alias trivy='docker run --rm -v "$PWD":/src -w /src aquasec/trivy:0.76.2'
alias checkov='docker run --rm -v "$PWD":/tf -w /tf bridgecrew/checkov:3.4.5'

# pre-commit 4.7.0
pipx install pre-commit==4.7.0 && pre-commit --version
TFLint version 0.66.0
+ ruleset.terraform (0.17.0-bundled)
pre-commit 4.7.0

Container image tags on Docker Hub: aquasec/trivy,bridgecrew/checkov the tags that actually exist take precedence (version numbers verified against GitHub releases). You can also install with apt / Homebrew / pipx; see each tool’s official documentation.

.tflint.hcl

config {
  call_module_type = "local"     # checks local module calls (default)
}

plugin "terraform" {
  enabled = true
  preset  = "recommended"        # includes unused_declarations, typed_variables, required_version, etc.
}

# Enable in the cloud lessons:
# plugin "azurerm" { enabled = true  version = "x.y.z"  source = "github.com/terraform-linters/tflint-ruleset-azurerm" }

rule "terraform_documented_variables" {
  enabled = true                 # in addition to recommended, requires variables to have a description
}

.pre-commit-config.yaml

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.109.5
    hooks:
      - id: terraform_fmt
      - id: terraform_validate
        args:
          - --hook-config=--retry-once-with-cleanup=true
      - id: terraform_tflint
        args:
          - --args=--config=__GIT_WORKING_DIR__/.tflint.hcl
      - id: terraform_trivy
        args:
          - --args=--severity=HIGH,CRITICAL
          - --args=--skip-dirs="**/.terraform"
  - repo: local
    hooks:
      - id: terraform-unit-tests
        name: terraform test (unit, mock)
        entry: bash -c 'cd modules/stack && terraform test -filter=tests/unit.tftest.hcl'
        language: system
        pass_filenames: false
        files: ^modules/stack/

terraform_trivy,terraform_tflint hooks require the command to be directly executable on this machine trivy/tflint command (aliases do not work for hooks; the binary must really be installed on PATH). For hook argument format, follow the pre-commit-terraform README.

Lab 7: set up quality gates for the repository (about 8 minutes)

fmt and validate
cd ~/tf-lab/myapp
terraform fmt -check -recursive -diff; echo "fmt exit=$?"
terraform validate
modules/stack/main.tf
--- old/modules/stack/main.tf
+++ new/modules/stack/main.tf
@@ -1,5 +1,5 @@
 resource "docker_network" "this" {
-  name    = "${var.name_prefix}-net"
+  name = "${var.name_prefix}-net"
 }
fmt exit=3
Success! The configuration is valid.

A non-zero exit code means some files need formatting; run terraform fmt -recursive to fix them. If your code is already tidy, exit=0 is shown directly.

tflint: write into .tflint.hcl (see the “Commands” tab)
tflint --init
tflint --recursive --format compact
Installing "terraform" plugin...
Installed "terraform" (source: github.com/terraform-linters/tflint-ruleset-terraform, version: 0.17.0)
main.tf:1:1: Warning - variable "app_image" should have a description (terraform_documented_variables)
modules/stack/variables.tf:56:1: Warning - variable "redis_image" is declared but not used ... (terraform_unused_declarations)
2 issue(s) found:

The sample output only shows the format; your results depend on your code. In the root module, deprecated external_port variables, if not deleted, will be reported terraform_unused_declarations . Fix and run again until there are no issues remaining.

Scan: the myapp stack and a deliberately insecure example
mkdir -p examples/insecure-s3
cat > examples/insecure-s3/main.tf <<'EOF'
# For demonstration only; do not apply
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

resource "aws_s3_bucket" "logs" {
  bucket = "demo-insecure-logs-bucket"
}

resource "aws_s3_bucket_public_access_block" "logs" {
  bucket                  = aws_s3_bucket.logs.id
  block_public_acls       = false
  block_public_policy     = false
  ignore_public_acls      = false
  restrict_public_buckets = false
}
EOF
trivy config --severity HIGH,CRITICAL modules/stack     # Docker resources: usually 0 issues
trivy config --severity HIGH,CRITICAL examples/insecure-s3
checkov -d examples/insecure-s3 --framework terraform --compact --quiet
Report Summary
┌─────────┬───────────┬───────────────────┐
│ Target  │   Type    │ Misconfigurations │
├─────────┼───────────┼───────────────────┤
│ main.tf │ terraform │         4         │
└─────────┴───────────┴───────────────────┘
main.tf (terraform)
Failures: 4 (HIGH: 4, CRITICAL: 0)
HIGH: Public access block does not block public ACLs
...
Check: CKV2_AWS_6: "Ensure that S3 bucket has a Public Access block"
	FAILED for resource: aws_s3_bucket.logs
Check: CKV_AWS_145: "Ensure that S3 buckets are encrypted with KMS by default"
	FAILED for resource: aws_s3_bucket.logs
...

The two tools have different rule sets, so their results complement each other. For risks you genuinely accept, write an inline ignore with a reason, for example by adding above the resource #trivy:ignore:<ID> or #checkov:skip=CKV_AWS_18:the log bucket itself does not need access logs; do not disable rules globally.

pre-commit: hook the checks into git commit: write .pre-commit-config.yaml (requires tflint and trivy to be on PATH; if you do not have trivy yet, you can first delete the terraform_trivy hook)
pre-commit install
pre-commit run --all-files
Terraform fmt............................................................Passed
Terraform validate.......................................................Passed
Terraform validate with tflint...........................................Passed
Terraform validate with trivy............................................Failed
- hook id: terraform_trivy
- exit code: 1
examples/insecure-s3/main.tf ... HIGH: 4
terraform test (unit, mock)..............................................Passed

As expected, the insecure example blocked the commit. In the course, you can exclude the example directory by adding exclude: ^examples/, or delete examples/.

rm -rf examples
git add -A && git commit -m "m7: lint and scan gates"

Case 1: scan noise leads to “ignore everything”

Problem: On day one, Checkov reported 600 issues, so the team added --soft-fail, and after three months nobody looked at the results. Approach: Create a baseline (checkov --create-baseline), and block only new issues; HIGH/CRITICAL must be fixed, the rest go to a backlog, and every skip needs a reason and a quarterly review. Limitation: The baseline file must also be reviewed, or it will quietly absorb new issues.

Case 2: tflint finds an invalid VM size

Problem: A misspelled Azure VM size passes validate, and the error only appears at apply, leaving a half-built stack. Approach: Enable tflint-ruleset-azurerm, which has a built-in list of valid sizes, so the check fails at the pre-commit stage. Limitation: The ruleset data must be updated with the plugin; pin the plugin version in .tflint.hcl and upgrade it regularly.

Case 3: local hooks and CI give different results

Problem: A developer's local tflint is out of date; the commit passes, and CI fails. Approach: CI and local development use the same .pre-commit-config.yaml, with tool versions pinned in the devcontainer / tool manifest (for example, the .tool-versions file for mise or asdf); CI uses a pinned tag of the official container image. Limitation: Pinning versions means you must upgrade them deliberately; leave that to Renovate / Dependabot.

Common errors and fixes

Failed to initialize plugins; Plugin "terraform" not found. Did you run "tflint --init"?

Fix: Run tflint --init; cache in CI ~/.tflint.d/plugins. If downloads fail often, set GITHUB_TOKEN.

Error: Missing required provider ... (terraform validate fails in CI)

Cause: init has not been run first. Fix:terraform init -backend=false -input=false then validate; the pre-commit hook’s --retry-once-with-cleanup=true will clean up on failure and .terraform retry.

terraform fmt exit status 3 / Terraform fmt....Failed - files were modified by this hook

Cause: The file format is not standard; the hook has already auto-fixed it. Fix:git add Commit the modified file again. Turning on format-on-save in the editor avoids this.

trivy: FATAL ... failed to download vulnerability DB / misconfig checks bundle

Cause: The first run needs to download the rule package, and the network is restricted. Fix: Configure a proxy or use a mirror (--checks-bundle-repository, check the parameter name in the Trivy docs); in CI, cache ~/.cache/trivy.

Executable `tflint` not found / Executable `trivy` not found (pre-commit)

Cause: The hook calls the binary on PATH directly, so the shell alias has no effect. Fix: Install the real binary, or in repo: local a hook that calls a container.

Command-line exercises
1. In CI, make only HIGH/CRITICAL IaC issues fail the build, and output SARIF.
trivy config --severity HIGH,CRITICAL --exit-code 1 --format sarif --output trivy.sarif .
2. Use one command to check the formatting of the whole repository (without modifying files) and show the diff.
terraform fmt -check -recursive -diff
Scenario analysis
Checkov reports that a bucket fails CKV_AWS_18 (access logging is not enabled). This bucket is itself the log bucket, and enabling access logging would create a loop. How would you handle this, and make sure it can be reviewed later?

Write an inline skip with a reason on the resource: #checkov:skip=CKV_AWS_18:this bucket is the access-log target, and enabling logging would create recursive logs; have the security lead approve it in the PR; record it in the risk register and set a review date. Do not disable the rule globally in --skip-check (otherwise similar issues in other buckets would also slip through).

Verified instructional video

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · Covers static checks, tests, and CI-related sections (tfsec in the video has been merged into Trivy)

No verified video specifically on tflint / Trivy / Checkov was found; a storyboard script is provided instead.

Official documentation

Video storyboard script (about 70 seconds)

This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: five conveyor-belt gates: fmt, validate, tflint, Trivy, Checkov; the code package passes through each in turn.
Narration: each of the five tools covers one kind of problem: formatting, syntax, best practices, and security configuration.
Shot 2 · 20–45s
Visual: an S3 bucket icon lights up red at the Trivy gate; the screen shows four HIGH findings.
Narration: security scanning catches issues such as public access and missing encryption at the code stage, without deploying anything.
Shot 3 · 45–70s
Visual: the git commit button is blocked by a pre-commit shield, and below it the CI pipeline shows the same shield.
Narration: pre-commit blocks at commit time; CI checks again with the same configuration, because local hooks can be skipped.
or score ≥ 70% on the quiz
← Module 6Module 8: version constraints, upgrades, and review →

Module 8 · version constraints, upgrades, and production-readiness review

52:00 – 60:00 · Constraints go in code, exact versions go in the lock file, and upgrades follow a process. Before going live, use a checklist and a script to answer “is this code ready for production?”
8 minutesTerraform 1.17.2 · 1.x compatibility promise1.17: provider requirements can use variable/local★★★★★
Learning objectivesPrerequisites: Lock file basics from Lesson 1; m1–m7 from this lesson. Importance:★★★★★

What: three layers of version control

ObjectWhere it is declaredExact version recorded inRecommended form
Terraform CLIterraform { required_version = "…" }Not recorded (pinned by the toolchain / CI image, for example .terraform-version, mise / asdf,hashicorp/setup-terraform the version argument)Root module "~> 1.17.0" or ">= 1.16, < 2.0"; modules declare lower bounds ">= 1.11"
providerrequired_providers { docker = { source, version } }.terraform.lock.hcl (committed to git)Root module "~> 4.7"; modules ">= 4.0, < 5.0"
usemodule { version = "…" } or ?ref=.terraform/modules/modules.json (not committed)Exact version or ~> x.y.0

constraint operators

SyntaxMeaningExamples (available versions 4.6.0, 4.7.0, 4.7.3, 4.8.1, 5.0.0)
= 4.7.0 or 4.7.0exact4.7.0
!= 4.7.3Exclude a specific version (often used to skip versions with bugs)Combined with other conditions
>= 4.7, < 5.0Range (comma = AND)4.7.0, 4.7.3, 4.8.1
~> 4.7Pessimistic constraint: only allow the rightmost component to increase → >= 4.7, < 5.04.7.0, 4.7.3, 4.8.1
~> 4.7.0>= 4.7.0, < 4.8.04.7.0, 4.7.3

Pre-release versions (such as 5.0.0-beta1) are selected only when the constraint names them exactly. The constraints for the same provider declared in multiple modules are merged (intersected): root module ~> 4.7 + child modules >= 4.0, < 5.0 → intersection >= 4.7, < 5.0; if the intersection is empty, init reports “no available releases match the given constraints”.

Why: why both constraints and lock files are needed

  • Constraints express “which versions we are compatible with” (intent),The lock file express “which version we actually tested” (fact). With constraints only, different people at different times get different versions on init; with only a lock file, nobody knows whether an upgrade is safe.
  • In the lock file, the hashes hashes guarantee that the downloaded provider binary has not been tampered with (zh: is the zip hash Registry publishes for each platform, and h1: is the hash of the unpacked directory). Team members working on different platforms need to complete the multi-platform hashes.
  • Terraform 1.x compatibility promise: within 1.x, the language, state format, and CLI workflow stay backward compatible, and minor upgrades usually need no code changes; but major provider upgrades (such as docker 3.x→4.x, azurerm 4.x→5.x; azurerm was 5.14.0 as of verification) may include breaking changes.

How: upgrade process

  1. Read: the Terraform CHANGELOG, the provider CHANGELOG and upgrade guides; mark deprecations and breaking changes.
  2. Change the constraint in a branch (provider major version) or run only terraform init -upgrade (upgrades within constraints), and commit the new lock file.
  3. Complete the platform hashes: terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64.
  4. Run plan in each environment: expect “No changes”; any change must be explained item by item (new defaults, attribute renames). Fix deprecation warnings.
  5. Run tests and scans (m6, m7), and after merging, apply in environment order (dev → staging → prod).
  6. CLI upgrade: first upgrade the CI image and required_version lower bound, then notify the team; once someone has written state with the new version, older clients may be required to upgrade (watch the terraform_version).

Changes in Terraform 1.17 worth noting (1.17.0, 2026-10-21; current 1.17.2)

  • Provider requirements can use variable / local (for example, to manage version numbers centrally).
  • -minimal-refresh Planning option: refresh only resources with changes, so plan is faster for large state (covered in depth in lesson 7).
  • Terraform Policy GA: plan/apply/query of -policies argument no longer needs an experimental build (lesson 5).
  • terraform test of mock_provider supports ephemeral resources.

When: production-readiness review checklist

CategoryChecksFrom module
StructureEnvironments reuse modules; modules have a description, types, and defaults; no provider blockm1
stateRemote backend, locking enabled, isolation by environment / component, versioned and encrypted bucket, state not in gitm2
Multiple instancesUse for_each for collections with identity; no unhandled count index dependenciesm3
RefactoringStructural changes come with moved / removed / import blocks; no unexpected destruction in planm4
ContractKey inputs have validation; dependency assumptions have precondition; health check uses checkm5
TestsUnit tests + expect_failures cover every validation; integration tests run on schedulem6
Qualityfmt / validate / tflint / Trivy / Checkov pass; pre-commit and CI are consistentm7
Versionsrequired_version, provider constraints, multi-platform hashes in the lock file, pinned CLI versionm8
Operationsplan -detailed-exitcode No drift; rollback / recovery plan; documentation (README, input/output tables)m8 / lessons 5 and 7

Comparison with similar tools

TerraformnpmHelmGo modules
Constraints~> 4.7^4.7.0Chart.yaml dependency rangesgo.mod minimum version selection
Lock file.terraform.lock.hcl (providers only)package-lock.jsonChart.lockgo.sum
Upgrade commandinit -upgradenpm updatehelm dependency updatego get -u
Common misconceptions① “~> 4.7 “Only allow 4.7.x” is wrong: it allows 4.8, 4.9, … up to before 5.0; if you only want patch updates, write ~> 4.7.0. ② “Not committing the lock file is more flexible”: this makes each machine / each CI run get different provider versions, and problems cannot be reproduced. ③ “Pinning exact versions in modules is safer”: exact constraints in a module conflict with the caller's constraints and cannot be intersected; a wide lower bound is enough for modules. ④ “Just run init -upgrade and then apply”: you must first run plan in each environment and explain every change.

Architecture diagram: constraint merging and the lock file

Root module versions.tfdocker ~> 4.7 modules/stackdocker >= 4.0, < 5.0 · http >= 3.4, < 4.0 intersectdocker >= 4.7, < 5.0http >= 3.4, < 4.0 Lock file already exists?Yes, and satisfied → reuseNo / -upgrade →choose the newest version that satisfies .lock.hclversion 4.7.0constraintsh1: …zh: … (each platform)Commit to git Module versions are not on this chain: they are determined by module.version / ?ref= and recorded in .terraform/modules/modules.json
Figure 8-1: constraints express intent, the lock file records facts

Flowchart: a major provider upgrade

Read the upgrade guideCHANGELOG Change constraints in a branchinit -upgrade providers lockMulti-platform hashes Run plan in each environmentExpect no changes test + scanCI gate Apply environment by environmentdev→stg→prod Unexplained changes in plan → stop and return to step 1
Figure 8-2: an upgrade is an ordinary change: branch, review, test, and release environment by environment

Interactive tool: version constraint calculator

Enter constraints (comma-separated for multiple conditions) to see which versions match and terraform init which one would be selected. The available version list comes from kreuzwerker/docker’s real release history (4.0.0–4.7.0) plus the hypothetical future version 5.0.0.

Core commands and options

CommandPurposeKey options / notes
terraform version -jsonCLI and provider versionsRecord in CI logs
terraform providersProvider requirement tree for each moduleDiagnose constraint conflicts
terraform init -upgradeUpgrade providers and modules within constraints, and rewrite the lock fileUse only in upgrade branches
terraform providers lock -platform=…Write hashes for multiple platforms:linux_amd64,linux_arm64,darwin_arm64,windows_amd64
terraform init -lockfile=readonlyForbid lock file changes in CIFail when the lock file and constraints disagree
terraform plan -detailed-exitcodeDrift / change detection0 no changes, 2 changes present, 1 error
terraform {
  required_version = "~> 1.17.0"     # allows 1.17.x patches; users on 1.16 should change this to ">= 1.16, < 2.0"
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.7"            # 4.7.0 released 2026-11-11
    }
    http = {
      source  = "hashicorp/http"
      version = "~> 3.6"            # 3.6.3
    }
  }
}
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
grep -A12 'kreuzwerker/docker' .terraform.lock.hcl | head -12
- Fetching kreuzwerker/docker 4.7.0 for linux_amd64...
- Retrieved kreuzwerker/docker 4.7.0 for linux_amd64 (signed by a HashiCorp partner, key ID ...)
...
Success! Terraform has updated the lock file.
provider "registry.terraform.io/kreuzwerker/docker" {
  version     = "4.7.0"
  constraints = ">= 4.0.0, ~> 4.7, < 5.0.0"
  hashes = [
    "h1:3qR9…=",
    "h1:Zf0k…=",
    "zh:0a1b…",
    "zh:1c2d…",
    ...
  ]
}

How to verify: Each provider in the lock file has multiple h1: (one per platform). Common mistake: Running init only on Linux, and then a Mac teammate runs init and gets a checksum mismatch. Production use: CI uses -lockfile=readonly, and any lock file change must go through a PR.

Lab 8: upgrade drill + production-readiness review script (about 8 minutes)

Tighten the constraints and complete the lock file: change the root module versions.tf to the production version from the “Commands” tab
cd ~/tf-lab/myapp
terraform init -backend-config=dev.s3.tfbackend
terraform providers
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
git diff --stat .terraform.lock.hcl
Providers required by configuration:
.
├── provider[registry.terraform.io/kreuzwerker/docker] ~> 4.7
├── provider[registry.terraform.io/hashicorp/http] ~> 3.6
└── module.stack
    ├── provider[registry.terraform.io/kreuzwerker/docker] >= 4.0, < 5.0
    └── provider[registry.terraform.io/hashicorp/http] >= 3.4, < 4.0
 .terraform.lock.hcl | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
Simulate an “upgrade”: downgrade first, then upgrade (to see what the lock file does)
sed -i 's/version = "~> 4.7"            # 4.7.0/version = "~> 4.6.0"          # drill/' versions.tf
terraform init -backend-config=dev.s3.tfbackend 2>&1 | grep -iE "locked|does not match|Error" | head -3
terraform init -upgrade -backend-config=dev.s3.tfbackend | grep docker
terraform plan -detailed-exitcode >/dev/null; echo "plan exit=$?"
git checkout versions.tf .terraform.lock.hcl && terraform init -upgrade -backend-config=dev.s3.tfbackend | grep docker
│ Error: Failed to query available provider packages
│ locked provider registry.terraform.io/kreuzwerker/docker 4.7.0 does not match configured version constraint ~> 4.6.0; must use terraform init -upgrade to allow selection of new versions
- Installing kreuzwerker/docker v4.6.0...
plan exit=0
- Installing kreuzwerker/docker v4.7.0...

The lock file blocked a silent version change; only an explicit -upgrade is what changes the version. A plan with no changes shows that 4.6 and 4.7 are compatible with this code; this is exactly the step in the upgrade process where “each environment’s plan shows no changes”.

Write a review script
#!/usr/bin/env bash
# Production-readiness review: check each item and score (run in the root module directory)
set -u
pass=0; fail=0
ok()  { echo "  [PASS] $1"; pass=$((pass+1)); }
bad() { echo "  [FAIL] $1"; fail=$((fail+1)); }
chk() { if eval "$2" >/dev/null 2>&1; then ok "$1"; else bad "$1"; fi; }

echo "== Version =="
chk "declare required_version"              "grep -rq 'required_version' --include='*.tf' ."
chk "lock file committed"                       "git ls-files --error-unmatch .terraform.lock.hcl"
chk "lock file contains multi-platform hashes (>=3 h1)"    "[ \$(grep -c 'h1:' .terraform.lock.hcl) -ge 3 ]"
echo "== State =="
chk "use remote backend"                   "grep -rqE 'backend \"(s3|azurerm|gcs|remote)\"' --include='*.tf' ."
chk "enable use_lockfile"                  "grep -qE '^use_lockfile *= *true' *.tfbackend"
chk "state not in git"                   "! git ls-files | grep -q 'tfstate'"
echo "== Quality =="
chk "terraform fmt"                      "terraform fmt -check -recursive"
chk "terraform validate"                 "terraform validate"
chk "tflint"                             "tflint --recursive"
chk "no :latest images"                    "! grep -rqE '\"[^\"]+:latest\"' --include='*.tf' ."
chk "all variables have description"           "[ \$(grep -rc '^variable ' --include='*.tf' . | awk -F: '{s+=\$2} END{print s}') -le \$(grep -rc 'description *=' --include='*.tf' . | awk -F: '{s+=\$2} END{print s}') ]"
echo "== Tests =="
chk "module unit tests"                        "(cd modules/stack && terraform test -filter=tests/unit.tftest.hcl)"
echo "== Drift =="
terraform plan -detailed-exitcode -lock-timeout=60s >/dev/null 2>&1; rc=$?
if [ $rc -eq 0 ]; then ok "plan has no drift"; elif [ $rc -eq 2 ]; then bad "plan has pending changes or drift"; else bad "plan failed to run"; fi

total=$((pass+fail)); echo; echo "Score: $pass / $total"
[ $fail -eq 0 ]
mkdir -p scripts && chmod +x scripts/readiness.sh   # after writing the content above
./scripts/readiness.sh; echo "exit=$?"
== Version ==
  [PASS] declare required_version
  [PASS] lock file committed
  [PASS] lock file contains multi-platform hashes (>=3 h1)
== State ==
  [PASS] use remote backend
  [PASS] enable use_lockfile
  [PASS] state not in git
== Quality ==
  [PASS] terraform fmt
  [PASS] terraform validate
  [PASS] tflint
  [PASS] no :latest images
  [FAIL] all variables have description
== Tests ==
  [PASS] module unit tests
== Drift ==
  [PASS] plan has no drift

Score: 12 / 13
exit=1

The script is a rough first pass with simple rules (for example, counting “description” can give false positives); its value is turning the checklist into something that runs every time. Fix the FAIL items (here, add descriptions to the root module’s variables), then commit: git add -A && git commit -qm "m8: version pins, readiness script".

Manual review: items the script cannot check (module interface design, whether the state split is appropriate, whether moved blocks should be kept, and whether scan ignores have reasons) are confirmed by reviewers in the PR, item by item, against the checklist in the “Theory” tab.

Case 1: the “Monday incident” without a lock file

Problem: The repository ignores .terraform.lock.hcl, and the constraint is >= 3.0. Over the weekend a provider released a new major version, and on Monday CI picked it up, so the plan showed large numbers of replacements. Approach: Commit the lock file and change the constraint to ~> 3.x, CI uses -lockfile=readonly, provider upgrades are raised as PRs by Renovate, with a plan attached. Limitation: The lock file needs multi-platform hashes; otherwise developers on different operating systems hit checksum failures.

Case 2: mixed CLI versions force the team to upgrade

Problem: An engineer applied the production state with the new CLI, and later operations by other people and the old CI image hit version-related errors. Approach:required_version State the allowed range; CI and development use the same version file (.terraform-version + tfenv / mise); upgrade the CLI as a planned change and notify everyone. Limitation: The 1.x compatibility promise lowers the risk, but a unified toolchain is still the cheapest safeguard.

Case 3: review finds state in the root of a shared bucket

Problem: During review we found that dev and prod use the same bucket and the same credentials, with keys that differ only in file name; dev’s CI credentials can read and write prod state. Approach: Move prod state to a bucket in a separate account (init -migrate-state), CI uses a separate OIDC role per environment (lesson 5); add “credential isolation” to the review checklist. Limitation: Freeze changes to prod during the migration.

Interactive troubleshooting decision tree (all topics in this lesson)

Work step by step from the symptom; each leaf node gives a diagnostic command and a fix.

Common errors

Error: Unsupported Terraform Core version ... This configuration does not support Terraform version 1.16.7. To proceed, either choose another supported Terraform version or update this version constraint.

Fix: Install a CLI that satisfies required_version the CLI (tfenv install 1.17.2 / mise), or relax the constraint after review.

Error: Failed to query available provider packages ... no available releases match the given constraints >= 4.0.0, ~> 3.6, < 5.0.0

Cause: The intersection of the root module and child module constraints is empty. Diagnosis:terraform providers. Fix: Unify the constraints (usually the root module is behind the major version the module requires).

Error: Failed to install provider ... the local package for registry.terraform.io/kreuzwerker/docker 4.7.0 doesn't match any of the checksums previously recorded in the dependency lock file

Cause: The lock file is missing the hash for the current platform, or the download was tampered with / rewritten by a proxy. Fix:terraform providers lock -platform=<your platform> and commit; on an untrusted network, check the proxy first.

Command-line exercises
1. Complete the lock file hashes for Linux (amd64, arm64) and macOS (arm64).
terraform providers lock -platform=linux_amd64 -platform=linux_arm64 -platform=darwin_arm64
2. Initialize in CI: do not allow the lock file to be modified, and run non-interactively.
terraform init -input=false -lockfile=readonly -backend-config=prod.s3.tfbackend
Scenario analysis
You are responsible for upgrading the azurerm provider from 4.x to 5.x (5.14.0 is the latest as of verification), which affects 6 environments and 40 module calls. Please give a plan.

① Read the 5.0 upgrade guide and list the affected resources and attributes (renames, removed deprecated attributes, changed defaults, etc.); ② first upgrade the modules: change the module constraint to >= 5.0, < 6.0, verify in the module tests and publish a new module version (with moved blocks where needed); ③ in a branch, change the root module to ~> 5.14,init -upgrade,providers lock multi-platform; ④ run plan in each environment, explain each difference line by line, and fix deprecations; ⑤ after tests and scans pass, apply in the order dev → staging → prod, observing between steps; ⑥ keep a rollback plan: commits with the old lock file and old constraints can be reverted at any time (as long as no apply has yet made irreversible state changes).

Verified teaching videos

▶
Terraform in 100 Seconds — Fireship
English · Minimal recap, suited to a final overall review at the end of the course
▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · Concept review (provider, state, workflow)

Official docs

Video storyboard script (about 80 seconds)

This courseware cannot generate video or MP3 directly; the storyboard and narration script are provided for a video tool to generate.

Shot 1 · 0–20s
Visual: a version-number ruler; ~> 4.7 covers 4.7 up to but not including 5.0, ~> 4.7.0 covers only 4.7.x.
Narration: a pessimistic constraint only lets the rightmost number increase. Write one more digit and the range gets one level narrower.
Shot 2 · 20–45s
Visual: the constraint looks like a funnel, the lock file like a lock locking 4.7.0, with hashes for several platforms listed alongside.
Narration: the constraint expresses intent, the lock file records facts. Commit the lock file, and make sure it includes hashes for every platform the team uses.
Shot 3 · 45–80s
Visual: checklist items are ticked off one by one, and finally the review script outputs a score of 13 out of 13.
Narration: before go-live, review with the checklist and script: remote state, locking, tests, scans, versions, no drift. Only when all pass is it production ready.
or score ≥ 70% on the “Quiz” tab
← Module 7Command cheat sheet →

Command cheat sheet

One-page summary of all commands, blocks and recommended configuration in this lesson
Terraform 1.17

Module (m1)

terraform init                 # must run after adding or changing a module
terraform get -update          # update remote modules only
terraform modules -json        # installed modules (1.10+)
terraform state list module.stack
echo 'module.stack.app_urls' | terraform console

Remote state and locking (m2)

terraform init -migrate-state -backend-config=dev.s3.tfbackend
terraform init -reconfigure -backend-config=staging.s3.tfbackend
terraform plan -lock-timeout=5m
terraform force-unlock LOCK_ID
terraform state pull > backup.tfstate
terraform workspace new|list|select|delete NAME

count / for_each / dynamic (m3)

count    = var.enabled ? 1 : 0
for_each = var.app_instances          # map or set(string)
name     = "${var.name_prefix}-${each.key}"
dynamic "labels" {
  for_each = var.labels
  content { label = labels.key  value = labels.value }
}

Refactoring blocks (m4)

moved   { from = docker_container.app[0]  to = docker_container.app["web1"] }
moved   { from = module.stack_staging     to = module.staging }
import  { to = docker_volume.redis_data   id = "myapp-redis-data" }
removed { from = module.staging  lifecycle { destroy = false } }
# terraform plan -generate-config-out=generated.tf

Validation (m5)

validation   { condition = contains(["dev","staging","prod"], var.environment)  error_message = "…" }
precondition { condition = var.environment != "prod" || docker_image.app.repo_digest != ""  error_message = "…" }
postcondition{ condition = contains([for n in self.network_data : n.network_name], docker_network.this.name)  error_message = "…" }
check "app_health" { data "http" "h" { url = "…/healthz" }  assert { condition = data.http.h.status_code == 200  error_message = "…" } }

Testing (m6)

terraform test
terraform test -filter=tests/unit.tftest.hcl -verbose
terraform test -junit-xml=report.xml
# run { command = plan  expect_failures = [var.x] }
# mock_provider "docker" { mock_resource "docker_container" { defaults = {…} } }
# override_resource { target = …  values = {…}  override_during = plan }

Static checks and scanning (m7)

terraform fmt -check -recursive -diff
terraform init -backend=false && terraform validate
tflint --init && tflint --recursive
trivy config --severity HIGH,CRITICAL --exit-code 1 .
checkov -d . --framework terraform --compact
pre-commit install && pre-commit run --all-files

Versions and review (m8)

terraform version -json
terraform providers
terraform init -upgrade
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
terraform init -lockfile=readonly
terraform plan -detailed-exitcode   # 0 no changes / 2 changes / 1 error
./scripts/readiness.sh

Quick troubleshooting table

Symptom / errorMost likely causeFirst stepSee
Module not installedNew module added, init not runterraform initm1
hashicorp/docker Does not existChild module missing required_providersterraform providersm1
Error acquiring the state lockLock held by another user / stale lockCheck Lock Info, and once the process is confirmed to be gone, force-unlockm2
Backend configuration changedChanged key / tfbackend-migrate-state or -reconfigurem2
Unexpected plan changes N to destroyAddress changed (renamed, moved into a module, count→for_each)Write a moved block; compare with git diffm3 / m4
Invalid for_each argumentKey unknown at plan time / type is listuse static keys,toset()m3
Cannot import non-existent remote objectWrong import ID formatcheck the Import section of the provider docsm4
Invalid value for variableBlocked by validationFix the input per error_messagem5
Missing expected failureValidation condition invertedCheck the conditionm6
tflint plugin not foundnot yet run tflint --inittflint --initm7
Lock file checksum mismatchMissing hash for current platformterraform providers lock -platform=…m8
does not match configured version constraintconstraint changed, but not yet -upgradeterraform init -upgrade (in the upgrade branch)m8

Recommended configuration snippets

bucket       = "acme-tfstate-prod"
key          = "myapp/prod/terraform.tfstate"
region       = "ca-central-1"
encrypt      = true
kms_key_id   = "alias/tfstate"
use_lockfile = true
# Do not write credentials; use OIDC / roles
terraform {
  required_version = ">= 1.11"
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = ">= 4.0, < 5.0"
    }
  }
}
# do not write a provider block in a module
← Module 8Capstone lab →

Capstone lab + Final quiz

Modularization + remote state + tests + scanning: refactor myapp into dev / staging environments that pass the production-readiness review
After class ≈ 40 minutesCombines all modules
Scenario myapp is about to enter “pre-production”. Review requirements: dev and staging use the same module,their own separate remote state and locks; staging may only use tagged module versions; all inputs are validated, and the module has unit and integration tests; formatting, lint and security scans must pass before commit; versions are pinned and the lock file contains multi-platform hashes; the review script passes fully in both environments. Everything runs in local Docker and an S3-compatible container, at zero cloud cost.
Prerequisite check (outputs of m1–m8)
cd ~/tf-lab/myapp
git log --oneline | head -8
terraform state list | head
s3cli s3 ls s3://tfstate --recursive
(cd modules/stack && terraform test -filter=tests/unit.tftest.hcl | tail -1)
b71e0d4 m8: version pins, readiness script
4a9c2f1 m7: lint and scan gates
...
docker_volume.redis_data
module.stack.docker_container.app["web1"]
...
2026-11-15 11:40:12      23110 myapp/dev/terraform.tfstate
Success! 6 passed, 0 failed.

If any item is missing, go back to the “Lab” tab of the corresponding module and complete it. If the S3-compatible container is not running: docker start s3 and re-export the credentials.

Tag module versions (m1, m8)
git tag -a stack-v1.0.0 -m "modules/stack 1.0.0: for_each instances, validations, tests"
git tag -l 'stack-*'
stack-v1.0.0
Create a separate staging root module and state (m2, m4)
# First clean up the leftover staging objects removed in m4 (they are no longer managed by any state)
docker rm -f myapp-stg myapp-stg-redis 2>/dev/null; docker network rm myapp-stg-net 2>/dev/null
mkdir -p envs/staging && cd envs/staging
cp ../../versions.tf ../../backend.tf .
sed 's#myapp/dev/#myapp/staging/#' ../../dev.s3.tfbackend > staging.s3.tfbackend
grep key staging.s3.tfbackend
provider "docker" {}

module "stack" {
  # Use only tagged module versions (demo with a local git repo; in real use this is the URL of the company Git server)
  source = "git::file:///home/USER/tf-lab/myapp//modules/stack?ref=stack-v1.0.0"

  name_prefix   = "myapp-stg"
  environment   = "staging"
  env           = { APP_ENV = "staging" }
  app_instances = {
    web1 = { port = 8090 }
    web2 = { port = 8091 }
  }
}

output "urls" {
  description = "staging instance addresses"
  value       = module.stack.app_urls
}
sed -i "s#/home/USER/#$HOME/#" main.tf
terraform init -backend-config=staging.s3.tfbackend
terraform apply -auto-approve
curl -s -o /dev/null -w "%{http_code}\n" localhost:8091/healthz
s3cli s3 ls s3://tfstate --recursive
key    = "myapp/staging/terraform.tfstate"
Initializing modules...
Downloading git::file:///home/student/tf-lab/myapp//modules/stack?ref=stack-v1.0.0 for stack...
- stack in .terraform/modules/stack/modules/stack
...
Apply complete! Resources: 6 added, 0 changed, 0 destroyed.

Outputs:

urls = {
  "web1" = "http://localhost:8090"
  "web2" = "http://localhost:8091"
}
200
2026-11-15 11:40:12      23110 myapp/dev/terraform.tfstate
2026-11-15 11:52:47      14873 myapp/staging/terraform.tfstate

The container names are myapp-stg-web1,myapp-stg-web2 (module default naming). If your Terraform cannot use git::file:// source (depends on go-getter and git versions), switch to source = "../../modules/stack" continue, and note in the acceptance checklist that “module version pinning” is incomplete. .terraform/ caches a copy of the module under it: later edits to modules/stack will not affect staging until you tag a new version and change ?ref=— this is exactly “staging uses only released versions”.

Verify state and lock isolation (m2)
cd ~/tf-lab/myapp && terraform apply     # stops at the confirmation prompt
cd ~/tf-lab/myapp/envs/staging && terraform plan | tail -1
s3cli s3 ls s3://tfstate/myapp/ --recursive | grep tflock
No changes. Your infrastructure matches the configuration.
2026-11-15 11:55:03        231 myapp/dev/terraform.tfstate.tflock

dev holding the lock does not affect staging: each key has its own lock. Return to terminal A and enter no.

Tests: unit + integration (m5, m6)
cd ~/tf-lab/myapp/modules/stack
terraform test -junit-xml=test-report.xml | tail -1
Success! 8 passed, 0 failed.

6 unit tests + 2 integration tests. Integration tests use the itest prefix and port 18090, which do not conflict with dev (8080/8082) or staging (8090/8091).

Quality gates (m7): add envs/staging , also include in pre-commit and tflint
cd ~/tf-lab/myapp
printf 'envs/*/.terraform/\n' >> .gitignore
terraform fmt -recursive
tflint --recursive --format compact
trivy config --severity HIGH,CRITICAL --exit-code 1 --skip-dirs '**/.terraform' .
pre-commit run --all-files
Terraform fmt............................................................Passed
Terraform validate.......................................................Passed
Terraform validate with tflint...........................................Passed
Terraform validate with trivy............................................Passed
terraform test (unit, mock)..............................................Passed
Version pinning and review (m8)
cd ~/tf-lab/myapp/envs/staging
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
cd ~/tf-lab/myapp
./scripts/readiness.sh | tail -3
(cd envs/staging && ../../scripts/readiness.sh | tail -3)
  [PASS] plan shows no drift

Score: 13 / 13
  [FAIL] module unit tests
...

When run in the staging directory, the script's modules/stack path does not exist — a real defect in the review script. Fix: add a parameter to the script MODULE_DIR (default modules/stack), and in staging pass MODULE_DIR=../../modules/stack; or skip this item in staging, since it uses the tagged and already tested module version. After the fix, both environments should score full marks.

git add -A && git commit -qm "final: staging env with own state, pinned module, gates"
Cleanup (optional): Lesson 3 moves to Azure, so the local stack can be kept for reference. To free resources:
(cd ~/tf-lab/myapp/envs/staging && terraform destroy -auto-approve)
(cd ~/tf-lab/myapp && terraform destroy -auto-approve)
docker rm -f s3      # S3-compatible container; data remains in ~/tf-lab/s3data
docker volume rm myapp-redis-data 2>/dev/null || true

Destroy resources first, then stop the state storage. Doing it in reverse would leave destroy unable to read state.

Acceptance checklist

Open-ended self-test (answer first yourself, then expand the reference answer)

1. Why must a resource moved into a module have a moved block? What exactly does moved change internally?

A resource address is determined by its code location; after moving into a module, the address gains the module.x prefix; Terraform by default reads “old address disappears + new address appears” as destroy + create. At the start of plan, moved rewrites the old address to the new address in memory. The prior state the provider sees is the original object, so the plan is a no-op, and apply only writes back the new address without calling ApplyResourceChange.

2. Describe S3 use_lockfile lock acquisition and release; when does a stale lock occur?

Acquire: PutObject <key>.tflock with If-None-Match: *, success means the lock is held; if it already exists, 412 is returned and Lock Info is read. Release: after confirming the ID, DeleteObject. If the process is killed, power is lost, or the runner is reclaimed, the delete never runs and a stale lock remains; after confirming the other process no longer exists, run force-unlock, then immediately run plan to check.

3. What scenarios suit workspaces versus “separate directory + separate key”?

workspaces suit temporary copies of the same code (feature branches, short-term tests) that share backend configuration and credentials; long-lived environments (dev/staging/prod) use a separate directory + separate key (even a separate bucket and account), which isolates credentials and permissions, makes differences explicit, and reduces blast radius.

4. What is the difference between validation, precondition, postcondition and check? Give an example of each.

validation: input rule (port 1024–65535), error; precondition: dependency assumption (prod image must have a digest), checked before planning the object, error; postcondition: object result (container attached to the correct network), checked after the result is obtained, error; check: runtime health (/healthz returns 200), last step, warning.

5. Why mock in unit tests? What can mocks not prove?

mocks let tests run without Docker or cloud accounts, in seconds at zero cost, and cover the naming logic and every validation (expect_failures). They cannot prove that the real API accepts these values or that resources can actually reach each other; that is what integration tests and check blocks are for.

6. What is the process for a major provider version upgrade? What role does the lock file play in it?

Read the upgrade guide → change the constraint in a branch → init -upgrade → providers lock multi-platform → run plan in each environment and explain the differences → tests and scans → apply environment by environment. The lock file ensures that, until an explicit -upgrade upgrade, everyone and CI use the same verified version, and binary integrity is checked by hash; the upgrade result appears as a lock file change in the PR.

Final quiz (12 questions, covering all modules)

← Cheat sheetSources and version notes →Course index← Lesson 1Lesson 3: Moving to the cloud platform (Azure) →

Sources and version notes

Verification basis for all technical facts in this lesson (verified on 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
Terraform CLILatest v1.17.2 (2026-11-11); 1.17.0 (2026-10-21): provider requirements can use variable/local,-minimal-refresh, Terraform Policy GA (-policies), mock_provider supports ephemeral resourcesGitHub releases · CHANGELOG
Feature introduced interraform modules -json 1.10; S3 native locking use_lockfile 1.11 GA (DynamoDB-related parameters deprecated); terraform test -junit-xml 1.11 GA; override_during 1.11; validation can reference other objects 1.9; cross-type moved 1.8 (requires provider support); test mock 1.7; test framework 1.6CHANGELOG.md for the v1.8–v1.11 branches · Tests · Mocking
S3 backenduse_lockfile (lock object <key>.tflock); endpoints.s3,use_path_style,skip_credentials_validation,skip_requesting_account_id,skip_region_validation,skip_metadata_api_check,skip_s3_checksum; workspace_key_prefix default env:; for S3-compatible services it is best effort; credentials go through -backend-config are stored in .terraform and planBackend Type: s3
removed / check / importof removed lifecycle.destroy, destroy-time provisioner; check runs as the last step of plan/apply, failures are warnings, and nested data sources support depends_on and providerremoved · check · import
Provider versionskreuzwerker/docker 4.7.0 (2026-11-11; 4.0.0 on 2026-04-03); hashicorp/http 3.6.3; hashicorp/random 3.9.1; hashicorp/aws 6.73.0; hashicorp/azurerm 5.14.0; terraform-aws-modules/vpc/aws 6.7.3 (2026-09-18)Terraform Registry · docker provider releases
Tool versionstflint v0.66.0 (2026-11-08, adds Terraform 1.17 support); tflint-ruleset-terraform v0.17.0 (2026-11-04); Trivy v0.76.2 (2026-11-05); Checkov 3.4.5 (2026-11-12); pre-commit-terraform v1.109.5 (2026-11-11); pre-commit v4.7.0 (2026-10-13)Project GitHub releases:tflint · trivy · checkov · pre-commit-terraform
MinIO and alternativesMinIO repository archived 2026-04-25, community edition distributed as source only, last GitHub release RELEASE.2025-10-15T17-29-55Z; Docker Hub minio/minio repository returned 404 when verified; RustFS 1.0.5 (Apache 2.0,rustfs/rustfs, ports 9000/9001, UID 10001, default credentials rustfsadmin)minio/minio · rustfs/rustfs
OpenTofuLatest 1.13.9 (mentioned in this lesson only in the comparison table; for differences such as state encryption, refer to the official docs)OpenTofu releases

Video verification notes

The following videos were verified for title and channel via the YouTube oEmbed endpoint on 2026-11-15: Fireship “Terraform in 100 Seconds” (tomUWcQ0P3k); TechWorld with Nana “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); freeCodeCamp.org “HashiCorp Terraform Associate Certification Course - Pass the Exam!” (V4waklkBC38); KodeKloud “Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide!” (YcJ9IeukJL8); HashiCorp, an IBM Company “Introduction to HashiCorp Terraform with Armon Dadgar” (h970ZBgKINg). freeCodeCamp.org “Terraform Course - Automate your AWS cloud infrastructure” (SLB_c_ayRMo) was also verified, reserved for lesson 4. oEmbed does not return durations or publish dates, so durations are not listed on the cards. No verified dedicated videos were found for S3 native locking, moved/import/removed blocks, terraform test and mock, or tflint/Trivy/Checkov, so storyboard scripts are provided instead. All videos are in English and were recorded before Terraform 1.17.

Voice narration notes

The “Voice” tab uses the browser’s Web Speech API (speechSynthesis, en-US) reads the narration script aloud in real time, English terms are pronounced with en-US, and the result depends on the voices installed in the operating system. This courseware's generation environment cannot call a TTS service, so no MP3 is embedded; for offline audio, hand the narration script to a TTS service such as Azure AI Speech to generate it.

Known limitations

← Capstone labCourse indexContinue: Lesson 3, Moving to the cloud platform (Azure) →