Terraform Lesson 2: From “it runs” to “production-ready”
- 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-configfor partial configuration, and understand S3 native lockinguse_lockfilehow it is acquired and released,force-unlockits risks, and how to isolate state by environment / component, and the pitfalls of workspaces. - Understand the difference between
countandfor_each’s instance addresses differences, and use themovedblock to safely migratecounttofor_each, and use thedynamicblock to generate nested blocks. - Use the
moved/import/removedblock to refactor code only, without touching infrastructure, and use-generate-config-outto generate import configuration, and explain how they differ fromterraform state mv/rm,terraform importdifferences. - Use
validation,precondition,postcondition,checkto catch errors at different stages; useterraform testtherunblock,command = plan,mock_provider,override_*to write unit and integration tests. - Set up
fmt → validate → tflint → Trivy/Checkov → testlocal and CI quality gates (pre-commit), and complete the checklist version constraints, the upgrade process and the production-readiness review.
1-hour time plan
| # | Time | Module | Core content | Animation / interactive | Lab (local Docker + myapp stack) |
|---|---|---|---|---|---|
| 0 | Before class | Bridge and warm-up | Check the Lesson 1 myapp stack, versions and state; if missing, rebuild in 3 min | Production-readiness self-check (10 items) | terraform plan No changes |
| 1 | 00–08 | Module design and reuse | Root module / child modules, variables and outputs as interfaces, module sources, Registry modules, version pinning, module composition principles | Module call tree: inputs → resources → outputs, and how the address prefix is applied module. prefix | Extract modules/stack, add a second instance: staging |
| 2 | 08–15 | Remote state, locking and isolation | backend configuration, partial configuration -backend-config,-migrate-state, S3 use_lockfile,force-unlock, split by environment / component, workspace | Core animation: two operators compete for the state lock (conditional write .tflock → 412 → release / stale lock) | S3-compatible container + state migration + concurrent lock demo |
| 3 | 15–22 | count, for_each and dynamic | instance addresses [0] vs ["key"], cascading rebuild when deleting a middle element,for_each ’s known-value requirements,dynamic | count / for_each address comparison simulator (delete one element and see the plan) | app multi-instance: migrating count → for_each |
| 4 | 22–30 | Refactoring: moved, import, removed | Declarative refactoring blocks vs state mv/rm,import blocks + -generate-config-out,removed + destroy = false | Core animation: how the moved block maps old addresses in state to new addresses (avoiding destroy and recreate) | Import manually created containers, remove from state |
| 5 | 30–37 | Validation: validation, pre/postcondition, check | Execution 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 timeline | Add port / image validation and health checks to the module check |
| 6 | 37–45 | terraform test and mock | .tftest.hcl,run,command = plan/apply,expect_failures,mock_provider,override_resource | Test runner: run block order, shared state, mock-generated values, cleanup | Module unit tests (mock) + integration tests (real Docker) |
| 7 | 45–52 | Static checks and security scanning | fmt,validate, tflint (ruleset), Trivy config, Checkov, pre-commit, CI gates | Quality-gate pipeline: which gate catches which defect | One-command pre-commit check; scan a deliberately insecure example |
| 8 | 52–60 | Version constraints, upgrades and production-readiness review | required_version, provider constraints and ~>, multi-platform hashes in the lock file, upgrade process, 1.17 new features, review checklist and script | Version constraint calculator + troubleshooting decision tree | Upgrade drill + run the review script |
| — | After class | Cheat sheet · Capstone lab | Production-readiness refactor: modularization + remote state + tests + scanning | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / blocks | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Design module interfaces and reuse them | ✓ | · | ✓ | · | ✓ | ✓ | · | · | module,variable,output | modules/stack |
| Reference and pin third-party module versions | ✓ | · | · | · | · | · | · | ✓ | source,version,?ref= | Registry module example |
| Remote state migration and locking | · | ✓ | · | · | · | · | · | ✓ | init -migrate-state,force-unlock | S3-compatible backend |
| Isolate state by environment / component | ✓ | ✓ | · | · | · | · | · | ✓ | -backend-config,workspace | dev / staging key |
| Multi-instance resources and stable addresses | · | · | ✓ | ✓ | · | · | · | · | count,for_each,dynamic | count → for_each |
| Lossless refactoring (no destroy and recreate) | ✓ | · | ✓ | ✓ | · | · | · | · | moved,state mv | Modularization migration |
| Bring existing resources under management / stop managing them | · | · | · | ✓ | · | · | · | · | import,removed,-generate-config-out | Import manually created containers |
| Input and runtime contract validation | ✓ | · | · | · | ✓ | ✓ | · | · | validation,precondition,check | Port / health check |
| Automated tests (mock / integration) | · | · | · | · | ✓ | ✓ | ✓ | · | terraform test,mock_provider | tests/*.tftest.hcl |
| Static checks and security scanning | · | · | · | · | · | · | ✓ | ✓ | tflint,trivy config,checkov | pre-commit |
| Version management and upgrades | ✓ | · | · | · | · | · | · | ✓ | init -upgrade,providers lock | Upgrade drill |
Out of scope for this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Azure Storage backend (azurerm), Entra ID authentication, real cloud resources | Everything in this lesson runs on local Docker, at zero cost | Lesson 3: Moving to a cloud platform (Azure) |
| Real AWS S3 backend deployment, KMS encryption, least-privilege IAM | This lesson only simulates the protocol with an S3-compatible container | Lesson 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 gate | Lesson 5: Automation operations |
| Multi-account / multi-subscription landing zones, Stacks, large-state splitting architecture | Belongs to the architecture topic | Lesson 6: Architecture in practice |
State corruption recovery, drift investigation, performance tuning (-parallelism,-minimal-refresh) | Belongs to deep troubleshooting | Lesson 7; this lesson's m8 troubleshooting tree provides the entry point |
How to use these course materials
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”.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).
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.
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)
- CompletedLesson 1: directory
~/tf-lab/myappcontains one stack managed withkreuzwerker/dockera local stack: networkmyapp-net, containermyapp-redis(redis:7-alpine), containermyapp(from the Docker lesson'smyapp: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
dockergroup; 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
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.
Module 1 · Module design and reuse
module.NAME is its namespace in state- Distinguish root module (the directory where you run
terraformcommands) and child module (called by amoduleblock 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.
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
variableblocks; the caller sets values by name in themoduleblock. 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
outputblocks; the caller reads them viamodule.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 ismodule.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 writerequired_providers(addconfiguration_aliasesif 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
terraform init: the module installer reads themoduleof eachsource/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. Changingsourceorversionmust be followed by re-runninginit(orterraform get).- 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 declaresource = "kreuzwerker/docker", otherwise it is treated ashashicorp/docker). - 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_urlreferences depend only on the resources that produce that output, so resources from different modules can be created in parallel. - 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
| Source | Syntax | How to pin the version | Use case |
|---|---|---|---|
| Local path | source = "./modules/stack" | same git commit as the caller (no version) | private modules within a single repo |
| Terraform Registry | source = "terraform-aws-modules/vpc/aws" | version = "~> 6.7" (only Registry sources support version argument) | Public / private Registry (HCP Terraform) |
| Git | source = "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 shorthand | source = "github.com/org/tf-modules//stack?ref=v1.4.0" | Same as above | Same as above |
| HTTP / S3 / GCS archive | source = "s3::https://s3.amazonaws.com/bucket/stack-1.4.0.zip" | Version in file name | Offline / 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 module | Helm Chart (K8s lesson) | Ansible Role | Bicep module | |
|---|---|---|---|---|
| Parameters | variable (strongly typed + validation) | values.yaml (optional schema) | defaults / vars | param (strongly typed) |
| Return values | output | None (relies on NOTES / naming conventions) | registered variables / facts | output |
| Version distribution | Registry / Git ref | Chart repository / OCI | Galaxy / Git | Bicep Registry (ACR) |
| State | shares one state with the caller | one Secret per release | Stateless | Azure deployment records |
.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
Flowchart: terraform init what happens for each source
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.
Core commands and arguments
| Command | Purpose | Key arguments / notes |
|---|---|---|
terraform init | Install modules and providers, initialize the backend | -upgrade Upgrade modules and providers within constraints; must be re-run after changing source/version |
terraform get | Download / update modules only | -update Check remote modules for new versions |
terraform modules -json | List 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.stack | List resource instances in a module | The filter argument is an address prefix |
terraform plan -target=module.stack_staging | Plan only one module (emergency use) | Do not rely on it day to day -target, as it skips drift detection for other resources |
terraform output -json | View root module outputs | Child module outputs must be re-exposed with output in the root module to be visible |
terraform console | Interactive evaluation | Trial 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)
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).
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
}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.
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).
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.
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 = { … }.
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)
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
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.
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.
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.
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.
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.
Module 2 · Remote state, locking and isolation
- Write the partial configuration (only the code contains
backend "s3" {}, and the rest goes in a*.tfbackendfile, passed in with-backend-config), and migrate local state to it safely with-migrate-statesafely. - 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 errorError acquiring the state lock; clear a stale lock withforce-unlockthe 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).
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 (PutObjectwithIf-None-Match: *, returning412 PreconditionFailed) to create a<key>.tflockobject next to the state. The olddynamodb_tablelocking 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=fileor-backend-config="key=value"atinittime.
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)
Lock():PutObject tfstate/myapp/dev/terraform.tfstate.tflock, withIf-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-timeoutretries or reports an error.RefreshState():GetObject terraform.tfstate, checkslineageandserial.- 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.
PersistState():PutObject terraform.tfstate, serial + 1.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 akill -9, leaving behind a stale lock.
Extra parameters needed for S3-compatible storage (MinIO etc.) (verified against the official S3 backend documentation)
| Parameter | Purpose | Local 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_style | Use http://host/bucket/key path-style addressing (old name force_path_style) | true |
skip_credentials_validation | Do not call STS to validate credentials | true |
skip_requesting_account_id | Do not query the account ID via IAM/STS | true |
skip_region_validation | Do not validate the region name as an AWS region | true |
skip_metadata_api_check | Do not access the EC2 instance metadata service | true |
skip_s3_checksum | Do not attach new checksum headers on upload (some S3-compatible implementations do not support them) | true |
use_lockfile | Enable S3 native locking | true (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)
| Approach | How | Pros | Risks / 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 / credentials | small blast radius; permissions can be isolated (dev credentials cannot read prod state); code differences are explicit | more directories, with modules (m1) removing duplication |
| Split by component | network, data and app belong to different root modules and keys | faster plans and smaller change impact; the network rarely changes, so it does not need to be planned with every app change | cross-state dependencies require passing values (output → variable, or terraform_remote_state / data source) |
| CLI workspace | Same directory terraform workspace new staging, multiple states under the same backend configuration | Quickly 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 backend | azurerm backend | HCP Terraform | OpenTofu | |
|---|---|---|---|---|
| Locking mechanism | .tflock Conditional writes (DynamoDB deprecated) | Blob lease | Built-in workspace lock | Terraform-native backend; also has state encryption |
| Encryption | SSE-S3 / SSE-KMS (encrypt,kms_key_id) | storage-service encryption + optional CMK | Managed by the platform | Client-side state encryption (since 1.7) |
| Where to learn | This module / Lesson 4 | Lesson 3 | Lesson 5 | — |
-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
env:/name/Sequence diagram: acquiring and releasing the lock
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.
Core commands and arguments
| Command | Purpose | Key arguments / notes |
|---|---|---|
terraform init -backend-config=FILE | Initialize the backend with partial configuration | can be repeated; can also -backend-config="key=myapp/dev/terraform.tfstate" |
terraform init -migrate-state | migrate existing state to the new backend | interactive confirmation; -force-copy skip confirmation in automation |
terraform init -reconfigure | ignore old backend settings and reconfigure (without migrating) | use when switching to another environment's key |
-lock-timeout=DURATION | wait and retry when the lock cannot be acquired | recommended in CI 5m; the default is 0 seconds, failing immediately |
terraform force-unlock LOCK_ID | Delete a stale lock | -force skip confirmation; can only unlock the currently configured backend |
terraform state pull / push | Download / upload raw state | push checks lineage and serial; -force extremely dangerous |
terraform workspace new/list/select/delete/show | Manage CLI workspaces | terraform.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)
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.# 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.
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.
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.
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.
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.
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.
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
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
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.
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.
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.
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.
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.
Module 3 · count, for_each and dynamic
- Write the
count,for_eachinstances' full addresses ([0]and["web1"]), and explain why deleting a middle element from a list makescountthe plan replace all the instances after it. - Know when to use
count(0/1 switches, identical copies), and when to usefor_each(instances with identity); know thatfor_each's keys must be known at plan time and cannot be sensitive values. - Use
movedblock to migrate myapp's multi-instance setup losslessly fromcounttofor_each; usedynamicblock to generate nested blocks from a map (container labels).
toset(). Importance:★★★★☆What: three “repetition” mechanisms
| Mechanism | Applies to | Instance key | Reference style |
|---|---|---|---|
count = N | resource, data, module | integer index [0]…[N-1] | count.index; external docker_container.app[0],docker_container.app[*].name |
for_each = map / set(string) | resource, data, module | string 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 blocks | The 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
- At plan time, first evaluate
count/for_eachexpression 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 reportsInvalid for_each argument. - 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.
for_each's keys cannot be sensitive values (keys appear in addresses and the UI). A list first needs to betoset(); object lists are often converted to a map:{ for s in var.svcs : s.name => s }.- 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 writemoved.
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 becomemodule.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_each | Bicep | CloudFormation | Pulumi | |
|---|---|---|---|---|
| Loop syntax | for_each / count | [for x in list: {...}] (by index) | Fn::ForEach (language extension) | Host-language loops |
| Instance identity | map key | index / name at deploy time | Logical ID | Resource name (URN) |
| Rename migration | moved block | In Azure, just keep the resource name unchanged | None (requires replacement or import) | aliases |
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
Flowchart: safe migration from count → for_each
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 / command | Purpose | Notes |
|---|---|---|
count = var.enabled ? 1 : 0 | Conditional creation | When referencing one(docker_container.x[*].id) can yield null or the value when 0/1 |
for_each = var.instances | Create from a map | each.key / each.value.port |
for_each = toset(var.names) | Create from a set of strings | each.key == each.value |
{ for k, c in docker_container.app : k => c.name } | Convert instance map into output | A for_each resource is itself a map |
dynamic "labels" { … } | Generate nested blocks from a collection | content { label = labels.key value = labels.value } |
terraform state list 'module.stack.docker_container.app' | List all instances | in 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 instance | Windows 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)
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
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.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.
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.
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.
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.
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 console2. In bash, view the for_each instance web3 's detailed attributes.
terraform state show 'module.stack.docker_container.app["web3"]'
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
No verified video specifically about “migrating count to for_each” was found; a storyboard script is provided.
Official documentation
- The count Meta-Argument
- The for_each Meta-Argument
- dynamic Blocks
- Refactoring (includes count/for_each migration)
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.
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.
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.
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.
Module 4 · Refactoring: moved, import, removed blocks
- 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
importblock (can includefor_each) +terraform plan -generate-config-out=generated.tfto bring manually created resources under management, and clean up the generated configuration. - Use
removedblock +lifecycle { destroy = false }to remove resources from state without destroying them; be able to compareterraform state mv/rm,terraform importcommands' pros and cons and make a choice.
What: three blocks, three intents
| Block | Intent | Minimal syntax | Introduced in | Equivalent old command |
|---|---|---|---|---|
moved | same 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 |
import | bring an existing real object into state | import { to = ADDR id = "…" } | 1.5 (for_each 1.7) | terraform import ADDR ID |
removed | remove a resource from code and specify whether the real object is destroyed | removed { from = ADDR lifecycle { destroy = false } } | 1.7 | terraform 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 mvif 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
- Before plan starts refreshing, Terraform core collects all moved statements across modules and validates:
tothe to address must exist in the configuration;fromthe from address must not still exist in the configuration; cycles are not allowed; chained moved (A→B, B→C) are merged in order. - For each match in state
fromobject: iftoaddress has no object in state yet, the address is changed in memory toto. Iftois already occupied, this moved is ignored and a warning is issued.fromIf it does not exist, it is silently skipped (so moved blocks in a module are harmless to new users). - After that the flow is the same as a normal plan: the provider's
PlanResourceChangereceives “prior state” that is the original object, so identical attributes mean no-op. The plan output# A has moved to B. - 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
- At plan time, for each import block, call the provider's
ImportResourceState(id), thenReadResourceread all attributes of the real object. - 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).
- 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. - 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
frompoints to a resource or module (cannot include an instance key, i.e. you cannot remove onlyapp["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-timelocal-exec/remote-execprovisioner.
When: which one to choose
| Scenario | Recommended | Notes |
|---|---|---|
| rename a resource / module call, move into a module, count→for_each | moved | make sure attributes are unchanged, otherwise replacement still happens |
| bring under management objects created manually or by other tools | import 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 B | In A, use removed { destroy = false } + in B, use import | moved cannot cross states; first import in B and apply, then remove in A |
| hand a resource to another team / tool | removed { destroy = false } | the other side takes it over with import |
| emergency fixes, one-off, single-person environments | state mv/rm (first -dry-run, first state pull back up) | you must still fix the corresponding code afterward |
Comparison with similar technologies
| Terraform blocks | state commands | Pulumi | CloudFormation | |
|---|---|---|---|---|
| Rename without rebuilding | moved | state mv | aliases | Not supported (requires Retain + import) |
| Bring existing objects under management | import block + generated config | terraform import | pulumi import (generated code) | Resource import / IaC generator |
| Stop managing | removed | state rm | pulumi state delete / retainOnDelete | DeletionPolicy: Retain |
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
Flowchart: splitting state (removed + import combined)
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.
Core blocks and commands
| Block / command | Purpose | Key points |
|---|---|---|
moved { from to } | Address migration | Can be used for resources, instances ([0],["k"]), module call (module.a → module.b) |
import { to id } | Import | id 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.tf | to generate resource blocks for imports that lack configuration | only supports the root module; the file must not already exist |
removed { from lifecycle { destroy = false } } | Stop managing | from without instance key |
terraform state mv -dry-run A B | Preview imperative migration | Remote backends also acquire locks |
terraform state rm -dry-run ADDR | Preview removal from state | real object is kept |
terraform state pull > backup.tfstate | Back up before surgery | Backup 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)
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
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.
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"
}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.
# 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.
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.tf2. 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 }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
No verified video specifically demonstrating moved / import / removed blocks was found; a storyboard script is provided.
Official documentation
- Refactoring (moved)
- Import (import block)
- Generating configuration
- removed block reference
- terraform state mv
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.
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.
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.
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.
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.