Terraform Hour 7: Deep Troubleshooting, Optimization, and Advanced Topics
- Build a fixed debugging methodology (reproduce → isolate → minimize → fix → prevent regression), and skillfully use
TF_LOG/TF_LOG_CORE/TF_LOG_PROVIDER/TF_LOG_PATH, able to tell apart in the logs Terraform core,provider gRPC calls and HTTP requests to cloud/local APIs, and useterraform graphto view the dependency graph. - Safely perform state surgery:
state list/show/mv/rm/pull/push/replace-provider,terraform show -json; understand lineage and serial protection, and recover corrupted state from MinIO (S3-compatible) object versions. - Read and understand Cycle,Invalid for_each argument (keys that depend on post-apply values), plan failures, and know
-targetwhen it is a lifesaving tool and when it is a hidden risk. - Identify provider issues: API throttling and retries (AWS
max_retries/retry_mode),timeoutsblocks, eventual consistency, and provider bugs such as “Provider produced inconsistent result”, including how to locate and report them. - Do performance analysis and optimization:
-parallelism,-refresh=false, new as of 1.17-minimal-refresh, provider plugin caching, splitting large stacks, and measuring the time spent on each resource with JSON logs. - Establish an upgrade process (Terraform CLI, provider major versions, multi-platform hashes in the lock file), and understand OpenTofu migration steps and major differences; be able to use
externaldata sources,terraform_dataextension capabilities, and get a minimal Plugin Framework provider working. - In the mixed fault blind box independently diagnose 8 randomly injected fault types and produce a performance optimization report.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (local Docker + MinIO) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: fault-injection repository | MinIO remote state, part7 example stack, fault-injection script faultbox.sh | Environment self-check | Apply baseline stack |
| 1 | 00–06 | Debugging methodology and TF_LOG | five-step method, log levels and routing, JSON logs, capturing the Docker API with socat,terraform graph | Core animation: log flow of one apply, core → gRPC → HTTP API | Split logs + packet capture comparison |
| 2 | 06–15 | State surgery | state mv/rm/pull/push/replace-provider,show -json, lineage/serial, backup and recovery | Core animation: state address changes before and after surgery | renaming, splitting, corruption recovery |
| 3 | 15–23 | Dependency cycles, unknown values, and plan failures | Cycle,-draw-cycles, for_each unknown keys,-target two-phase apply | dependency graph topological sort and cycle detection simulator | Reproduce and fix Cycle and unknown-key errors |
| 4 | 23–30 | Provider issues and API throttling | retries and backoff,timeouts, eventual consistency, provider bug identification and reporting | Throttling 429 + exponential backoff simulator | Health check timeout + inconsistent results |
| 5 | 30–38 | Performance | -parallelism,-refresh=false,-minimal-refresh, plugin cache, stack splitting, timing analysis | parallelism and refresh strategy timer | 50-resource benchmark |
| 6 | 38–45 | Upgrading Terraform and providers | upgrade process,terraform version, lock file, major-version migration guide, OpenTofu | upgrade pipeline gate simulation | docker provider upgrade + tofu trial migration |
| 7 | 45–52 | Custom extensions | external,terraform_data, Plugin Framework basics,dev_overrides | external protocol / provider RPC sequence | Write a minimal provider |
| 8 | 52–60 | Mixed fault blind box | 8 random fault types: injection, diagnosis, fix, review | in-browser fault simulator + troubleshooting tree | Blind box challenge |
| — | After class | Cheat sheet · Integrated lab | Fault blind box scoring challenge + performance optimization report | Final quiz (12 questions) | Integrated lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Layered diagnosis: core / provider / API | ✓ | · | ✓ | ✓ | · | · | ✓ | ✓ | TF_LOG_CORE,TF_LOG_PROVIDER | M1 log routing |
| Dependency graph analysis | ✓ | · | ✓ | · | ✓ | · | · | ✓ | terraform graph -type=plan -draw-cycles | Cycle reproduction |
| State refactoring and repair | · | ✓ | · | · | ✓ | ✓ | · | ✓ | state mv/rm/pull/push | renaming, splitting stacks |
| State backup, corruption, and recovery | · | ✓ | · | · | · | ✓ | · | ✓ | mc ls --versions,force-unlock | version rollback |
| Unknown values and plan failures | · | · | ✓ | · | · | · | ✓ | ✓ | -target, static keys | for_each fix |
| Provider throttling, timeouts, consistency | ✓ | · | · | ✓ | ✓ | · | · | ✓ | timeouts,max_retries | health check timeout |
| Performance optimization and measurement | ✓ | · | · | ✓ | ✓ | · | · | · | -parallelism,-minimal-refresh | 50-resource benchmark |
| Upgrade and migration (including OpenTofu) | · | ✓ | · | · | · | ✓ | · | ✓ | init -upgrade,providers lock,tofu | provider upgrade |
| Custom extensions | · | · | · | · | · | · | ✓ | · | external,terraform_data,go build | minimal provider |
Topics excluded from this hour (and where to learn them)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| Basic syntax of moved / import / removed blocks | Covered in Lesson 2; this hour only compares it within state surgery | Hour 2 · Module 4 |
| State splitting architecture and cross-stack reference design | Belongs to the architecture topic | Hour 6 · Module 3 |
| plan/apply pipelines in CI/CD, OIDC | Belongs to the automation topic | Hour 5 |
| Full provider development (complete CRUD, acceptance tests, publishing to the Registry, signing) | Takes hours; this hour only offers an introduction to “read it, reproduce it, and file an issue” | Official Plugin Framework tutorial |
| Writing rules for Terraform Policy / Sentinel / OPA | Belongs to the governance topic | Lesson 5 and official documentation |
| 50 production issues and interview questions | Lesson 8 (optional) covers this in depth | Hour 8 |
How to use this courseware
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. This hour is a troubleshooting hour: for each module, first do the fault injection in “Lab”, then go back and read “Principles”.
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress, saved in this browser (if local storage is disabled, progress is cleared on refresh).
The “Voice” page reads the narration aloud with the browser's built-in Web Speech API (en-US); if no Chinese voice pack is installed, the narration can still be read or passed to a TTS tool.
-minimal-refresh (refreshing only resources with proposed changes), provider requirements can reference variable/local, Terraform Policy GA. 1.16.x still gets patches (1.16.7). Local lab provider: kreuzwerker/docker 4.7.0 (2026-11-11),hashicorp/random,hashicorp/local,hashicorp/external. OpenTofu is currently at 1.13.x (1.13.9, 2026-11-05; 1.12.x still maintained). The latest Plugin Framework v1.19.0 (2026-03). All version numbers were verified on 2026-11-15; other details not listed here follow the official documentation.Module 0 · Preparation: fault-injection repository (complete before class)
- Completed Lessons 1–6: familiar with resource / module / for_each / backend / moved / import; Lesson 2 used MinIO to simulate an S3 backend.
- Workstation: Ubuntu 24.04 LTS (Azure VM or local machine/WSL2), Docker Engine 29.x (from the Docker course), current user in the
dockergroup. - Installed: Terraform 1.17.x,
jq,socat,graphviz(dot), Go (used in Module 7; version requirements follow the Plugin Framework documentation). Optional: OpenTofu 1.13.x (Module 6).
Connection to the previous lesson
Lesson 6 split a multi-environment stack into several states (network / data / app) and used ephemeral resources to handle secrets. This hour shifts the focus from “how to design” to “how to fix it when it breaks”: we deliberately use a small but complete local stack (network + nginx/myapp + redis + random name + local file), store its state on MinIO, and then break it repeatedly. The state splitting you learned in Lesson 6 is exactly the scenario for state mv the cross-state migration use case.
Step 1: install tools and confirm versions
sudo apt-get update && sudo apt-get install -y jq socat graphviz
terraform version
docker version --format '{{.Server.Version}}'
Terraform v1.17.2 on linux_amd64 29.9.3
Step 2: start MinIO (S3-compatible state backend) and enable object versioning
If the Lesson 2 minio container is still running, reuse it; otherwise run the command below. Enabling bucket versioning is a prerequisite for recovering corrupted state in Module 2.
docker network create tf-lab 2>/dev/null || true docker run -d --name minio --network tf-lab -p 9000:9000 -p 9001:9001 \ -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin \ -v minio-data:/data pgsty/minio:RELEASE.2026-08-04T00-00-00Z server /data --console-address ":9001" # Create the bucket and enable versioning with the mc client built into the minio image docker exec minio mc alias set local http://127.0.0.1:9000 minioadmin minioadmin docker exec minio mc mb --ignore-existing local/tfstate docker exec minio mc version enable local/tfstate docker exec minio mc version info local/tfstate
Added `local` successfully. Bucket created successfully `local/tfstate`. local/tfstate versioning is enabled local/tfstate versioning is enabled
minioadmin/minioadmin For local lab use only; do not expose the ports to the public internet (do not allow 9000/9001 in the Azure VM's NSG). Production state backends should use cloud object storage + encryption + least privilege.Step 3: create the part7 example stack
mkdir -p ~/tf-lab/part7/app && cd ~/tf-lab/part7/app export AWS_ACCESS_KEY_ID=minioadmin AWS_SECRET_ACCESS_KEY=minioadmin
terraform {
required_version = "~> 1.17"
required_providers {
docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
random = { source = "hashicorp/random", version = "~> 3.7" }
local = { source = "hashicorp/local", version = "~> 2.5" }
}
backend "s3" {
bucket = "tfstate"
key = "part7/app.tfstate"
region = "us-east-1" # MinIO does not validate this, but the parameter is required
endpoints = { s3 = "http://127.0.0.1:9000" }
use_path_style = true
use_lockfile = true # S3 native locking (.tflock object), no longer requires DynamoDB
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
skip_region_validation = true
skip_s3_checksum = true # some S3-compatible implementations do not accept checksum headers
}
}
provider "docker" {} # defaults to unix:///var/run/docker.sock; can be overridden with DOCKER_HOST
variable "app_image" {
type = string
default = "nginx:1.29-alpine" # can also be replaced with the myapp:1.0 image built in the Docker course
}
variable "web_count" {
type = number
default = 2
}
resource "random_pet" "suffix" { length = 2 }
resource "docker_network" "lab" {
name = "p7-${random_pet.suffix.id}"
}
resource "docker_image" "app" {
name = var.app_image
keep_locally = true
}
resource "docker_image" "redis" {
name = "redis:7.4-alpine"
keep_locally = true
}
resource "docker_container" "redis" {
name = "p7-redis"
image = docker_image.redis.image_id
networks_advanced { name = docker_network.lab.id }
}
resource "docker_container" "web" {
count = var.web_count
name = "p7-web-${count.index}"
image = docker_image.app.image_id
env = ["REDIS_HOST=${docker_container.redis.name}"]
networks_advanced { name = docker_network.lab.id }
ports {
internal = 80
external = 8080 + count.index
}
}
resource "local_file" "inventory" {
filename = "${path.module}/inventory.txt"
content = join("\n", [for c in docker_container.web : "${c.name} ${c.network_data[0].ip_address}"])
}
output "web_urls" { value = [for i in range(var.web_count) : "http://localhost:${8080 + i}"] }
terraform init
terraform apply -auto-approve
terraform state list
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080
Initializing the backend... Successfully configured the backend "s3"! Terraform will automatically use this backend unless the backend configuration changes. Initializing provider plugins... - Installing kreuzwerker/docker v4.7.0... ... Apply complete! Resources: 9 added, 0 changed, 0 destroyed. docker_container.redis docker_container.web[0] docker_container.web[1] docker_image.app docker_image.redis docker_network.lab local_file.inventory random_pet.suffix 200
Step 4: fault-injection script faultbox.sh
The script ~/tf-lab/part7/app does reversible disruptions: each fault first backs up the git stash current state and writes the injection number to .fault (hidden in blind-box mode). Module 8 and the integrated lab use it repeatedly.
#!/usr/bin/env bash
# Usage: ./faultbox.sh inject [1-8|random] ./faultbox.sh reset
set -euo pipefail
APP=~/tf-lab/part7/app; cd "$APP"
[ -d .git ] || { git init -q; git add -A; git commit -qm baseline; }
fault=${2:-random}; [ "$fault" = random ] && fault=$(( RANDOM % 8 + 1 ))
case "${1:-}" in
reset)
git checkout -q -- . ; git clean -qfd -e .terraform -e .terraform.lock.hcl
sudo systemctl start docker 2>/dev/null || true
rm -f .fault; echo "Baseline code restored (you must fix the state yourself!)"; exit 0;;
inject) echo "$fault" > .fault ;;
*) echo "usage: $0 inject [1-8|random] | reset"; exit 1;;
esac
case $fault in
1) # stale lock: killed with kill -9 during apply
( terraform apply -auto-approve -var web_count=3 >/dev/null 2>&1 & pid=$!; sleep 4; kill -9 $pid ) || true ;;
2) # drift: someone manually deleted the container
docker rm -f p7-web-1 >/dev/null ;;
3) # dependency cycle: redis references web, and web references redis
sed -i 's|name = "p7-redis"|name = "p7-redis"\n env = ["WEB=${docker_container.web[0].name}"]|' main.tf ;;
4) # for_each keys depend on values known only after apply
cat >> main.tf <<'EOF'
resource "random_id" "tag" { byte_length = 2 }
resource "local_file" "per_tag" {
for_each = toset(["a-${random_id.tag.hex}", "b-${random_id.tag.hex}"])
filename = "${path.module}/${each.key}.txt"
content = each.key
}
EOF
;;
5) # provider cannot connect to the Docker API
echo 'export DOCKER_HOST=tcp://127.0.0.1:2399' > .envrc-fault
echo "Run: source .envrc-fault" ;;
6) # resource renamed without a moved block → plan wants to destroy and recreate
sed -i 's/resource "docker_container" "redis"/resource "docker_container" "cache"/; s/docker_container.redis/docker_container.cache/g' main.tf ;;
7) # lock file hash tampered with
sed -i '0,/"h1:/s/"h1:[A-Za-z0-9+\/=]*"/"h1:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="/' .terraform.lock.hcl
rm -rf .terraform/providers ;;
8) # old state pushed back: creates a serial/lineage conflict
terraform state pull > /tmp/p7-old.tfstate
terraform apply -auto-approve -var web_count=1 >/dev/null
cp /tmp/p7-old.tfstate /tmp/p7-stale.tfstate # serial is older than the remote
echo "Someone is about to run: terraform state push /tmp/p7-stale.tfstate" ;;
esac
echo "Fault injected (in blind-box mode, do not peek at .fault). Start diagnosing: terraform plan"
chmod +x ~/tf-lab/part7/faultbox.sh cd ~/tf-lab/part7/app && git init -q && printf '.terraform/\n*.tfstate*\n.fault\n' > .gitignore && git add -A && git commit -qm baseline ~/tf-lab/part7/faultbox.sh reset
random_id, which belongs to the declared hashicorp/random, so required_providers does not need to be changed again. Faults 1 and 8 actually modify the state in MinIO,reset only the code is restored; the state must be repaired with this hour's methods, which is the point of the exercise.Warm-up: answer from memory (30 seconds)
What are the three phases of terraform plan?
① Read the configuration and build the dependency graph; ② refresh: call the provider's ReadResource, obtaining the current real-world values; ③ call PlanResourceChange to compute expected values and differences. Module 5's -refresh=false and -minimal-refresh work on step ②.
What does state store? Which two fields protect it from being overwritten?
Resource address → actual attributes (including ID), dependencies, output values, provider address. lineage (a UUID generated at creation, identifying “this is the history of the same state”) and serial (incremented on every write) prevent an old state or an unrelated state from overwriting the new one.
Module 1 · Debugging methodology and TF_LOG
- Follow the five-step method “reproduce → isolate → minimize → fix → prevent regression” instead of guessing from error keywords.
- Master
TF_LOG(TRACE/DEBUG/INFO/WARN/ERROR/JSON),TF_LOG_CORE,TF_LOG_PROVIDER,TF_LOG_PATHcombinations, and know thatTF_LOG_PATHsetting it alone produces no logs. - Find provider startup and gRPC methods (
GetProviderSchema,ConfigureProvider,ReadResource,PlanResourceChange,ApplyResourceChange); and be able to useterraform graphto draw the dependency graph.
What: where Terraform's logs come from
Terraform is a plugin architecture of “one core process + several provider subprocesses”. Core parses configuration, builds the dependency graph, traverses it, and manages state; each provider is a separate executable, and core communicates through go-plugin a gRPC interface, gRPC (Plugin Protocol v5/v6) to call it; the provider in turn calls the real API (HTTPS APIs for AWS/Azure, the HTTP API over the Docker Engine's unix socket). So logs naturally fall into three layers:
| Layer | Typical log prefix / content | Responsible party | How to view only this layer |
|---|---|---|---|
| Core | [INFO] Terraform version,backend/s3,[TRACE] vertex "docker_container.web[0]",[TRACE] GRPCProvider: PlanResourceChange | HashiCorp terraform repository | TF_LOG_CORE=TRACE |
| Provider | provider.terraform-provider-docker_v4.7.0: ...,@module=docker, SDK Calling downstream | provider repository (e.g. kreuzwerker/terraform-provider-docker) | TF_LOG_PROVIDER=DEBUG |
| API | AWS provider's HTTP Request Sent / HTTP Response Received (DEBUG level); the Docker provider does not print raw HTTP, so socat is needed to capture the socket | cloud vendor / Docker Engine | TF_LOG_PROVIDER=DEBUG or packet capture |
Environment variables (official Debugging Terraform page, verified 2026-11)
| Variable | Value | Description |
|---|---|---|
TF_LOG | TRACE / DEBUG / INFO / WARN / ERROR / JSON | Enables core and provider logs at the same time, written to stderr. JSON Outputs parseable JSON lines at TRACE level; the official docs explicitly state that JSON format is not a stable interface. |
TF_LOG_CORE | Same level | Enables only Terraform's own logs |
TF_LOG_PROVIDER | Same level | Enables only provider plugin logs |
TF_LOG_PATH | File path | Writes logs in append mode to a file. A log level must also be set; otherwise no logs are produced. |
Why: why you can't just read the error
Terraform's final error is often a provider's wrapping of an API error, or a secondary error from core during graph traversal. For example, “context deadline exceeded” could be a slow API, network DNS, exhausted provider retries, or a timeouts timeout that was set too short. Only the HTTP requests and timestamps tell them apart. Logs are also the first thing maintainers ask for when you file a provider issue.
How: five-step troubleshooting method
- Reproduce: record
terraform version(including provider version), the command run, variables, and workspace; can it be reproduced consistently on the same commit? - Isolate: at which step does the error occur: init (download/lock file/backend), validate (syntax/types), plan (refresh, graph building, unknown values), or apply (API calls, consistency checks)? Does it belong to core, the provider, or the API?
- Minimize: use
-target(diagnostics only), a minimal configuration in a separate directory,terraform consoleevaluate expressions to narrow it down to one resource or one expression. - Fix: change configuration, repair state, upgrade/downgrade providers, adjust timeouts/retries; verify with plan before applying.
- Prevent regression: add validation/precondition/check,
terraform test, pin versions in CI, and write a postmortem.
When: which level for which scenario
- INFO/WARN: can stay on long-term in routine CI and be written to a file; small in size, and shows backend and provider versions.
- DEBUG: investigate API errors (the AWS provider prints HTTP requests/responses at DEBUG).
- TRACE: investigate graph traversal order, gRPC calls, and unknown-value propagation; very large (a medium plan can reach tens of MB).
- JSON: need to use
jqto measure timing and filter by module (Module 5).
Comparison with similar tools
| Terraform | OpenTofu | Ansible | kubectl | |
|---|---|---|---|---|
| Enable verbose logs | TF_LOG=DEBUG | TF_LOG (compatible; same-named variable) | -vvvv | -v=8 (prints the HTTP request body) |
| Per component | TF_LOG_CORE/TF_LOG_PROVIDER | Same as | callback plugin | None |
| dependency graph | terraform graph (DOT) | tofu graph | None (sequential execution) | None |
TF_LOG_PATH produces logs”: it does not; you must also set a level. ② “TRACE logs can be pasted freely into an issue”: logs may contain provider configuration, request headers, and secrets in resource attributes (though the SDK tries to redact them), so check and redact before pasting. ③ “terraform graph shows the execution order”: the default output shows simplified resource dependencies, not the actual execution graph; to see the real plan/apply graph, use -type=plan / -type=apply.Architecture diagram: three sources of logs during one apply
Flowchart: five-step troubleshooting decisions
Core animation: log flow of one apply with TF_LOG=TRACE
Using terraform apply create docker_container.web[0] as an example, step through how logs flow from core → provider gRPC → Docker Engine HTTP API. Toggle the switches below to see which lines appear for TF_LOG_CORE and TF_LOG_PROVIDER (grey lines are not output under the current settings).
Core commands and parameters
| Command / variable | Purpose | Key parameters / notes |
|---|---|---|
TF_LOG=DEBUG terraform plan | core + provider logs to stderr | Levels: TRACE > DEBUG > INFO > WARN > ERROR; JSON |
TF_LOG_CORE / TF_LOG_PROVIDER | control the two layers separately | different levels can be set, e.g. core=WARN, provider=DEBUG |
TF_LOG_PATH=./tf.log | append to file | a level must also be set; clear the file manually before each run or use a timestamped file name |
terraform graph | output the dependency graph in DOT format | -type=plan|plan-refresh-only|plan-destroy|apply,-plan=tfplan,-draw-cycles (requires -type) |
terraform console | interactive expression evaluation | can read values from state, to locate expression errors |
terraform version -json | print CLI and provider versions | required for filing issues; since 1.17 JSON includes format_version |
socat -v | proxy docker.sock and print HTTP traffic | TCP-LISTEN:2375,fork UNIX-CONNECT:/var/run/docker.sock |
1. Split routing: core shows only warnings, the provider shows DEBUG, written to a file
cd ~/tf-lab/part7/app export TF_LOG_CORE=WARN TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=./tf-$(date +%H%M%S).log terraform plan -out=tfplan >/dev/null unset TF_LOG_CORE TF_LOG_PROVIDER TF_LOG_PATH ls -lh tf-*.log; grep -c 'provider.terraform-provider-docker' tf-*.log
-rw-r--r-- 1 azureuser azureuser 412K Nov 15 10:12 tf-101207.log 1873
How to verify: almost every line in the log carries the provider.terraform-provider-docker_v4.7.0 prefix. Common errors: Forgetting unset, every later command keeps appending to the log, and the file grows rapidly. Production use: set TF_LOG=INFO TF_LOG_PATH=$RUNNER_TEMP/tf.log in CI, and upload logs as artifacts on failure (mind redaction).
2. Find the provider lifecycle and gRPC calls
TF_LOG=TRACE terraform plan 2>&1 | grep -E 'starting plugin|plugin started|GRPCProvider: [A-Za-z]+|plugin exited' | head -20
2026-11-15T10:14:02.118Z [DEBUG] provider: starting plugin: path=.terraform/providers/registry.terraform.io/kreuzwerker/docker/4.7.0/linux_amd64/terraform-provider-docker_v4.7.0 args=[...] 2026-11-15T10:14:02.131Z [DEBUG] provider: plugin started: path=.terraform/providers/.../terraform-provider-docker_v4.7.0 pid=48213 2026-11-15T10:14:02.140Z [TRACE] GRPCProvider: GetProviderSchema 2026-11-15T10:14:02.402Z [TRACE] GRPCProvider: ValidateProviderConfig 2026-11-15T10:14:02.415Z [TRACE] GRPCProvider: ConfigureProvider 2026-11-15T10:14:02.530Z [TRACE] GRPCProvider: ReadResource 2026-11-15T10:14:02.611Z [TRACE] GRPCProvider: PlanResourceChange 2026-11-15T10:14:02.890Z [DEBUG] provider: plugin exited
method names may vary slightly across Terraform versions (for example ValidateProviderConfig/ValidateResourceConfig); follow your own logs. A provider may be started several times in one run (once each for validate and plan).
3. JSON logs + jq: filter by module and level
TF_LOG=JSON TF_LOG_PATH=./tf.json terraform plan >/dev/null jq -r 'select(."@level"=="error" or ."@level"=="warn") | [."@timestamp", ."@module", ."@message"] | @tsv' tf.json | head jq -r '."@module" // "core"' tf.json | sort | uniq -c | sort -rn | head
9421 core
1873 provider.terraform-provider-docker_v4.7.0
310 provider.terraform-provider-random_v3.7.2
122 provider.terraform-provider-local_v2.5.3
JSON keys (@level,@message,@module,@timestamp) are like this in the current version, but the official docs state that JSON logs are not a stable interface, so make scripts tolerant of changes.
4. Capture Docker Engine HTTP requests (API layer)
# Terminal A: proxy TCP 2375 to docker.sock and print the traffic (listen on 127.0.0.1 only) socat -v TCP-LISTEN:2375,bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/var/run/docker.sock 2>&1 | grep -E '^(GET|POST|DELETE|HEAD|PUT) |^HTTP/1.1 ' # Terminal B: make the provider use this proxy DOCKER_HOST=tcp://127.0.0.1:2375 terraform apply -auto-approve -var web_count=3
HEAD /_ping HTTP/1.1 HTTP/1.1 200 OK GET /v1.52/containers/json?all=1&filters=... HTTP/1.1 POST /v1.52/containers/create?name=p7-web-2 HTTP/1.1 HTTP/1.1 201 Created POST /v1.52/networks/1f0c.../connect HTTP/1.1 POST /v1.52/containers/7d1e.../start HTTP/1.1 HTTP/1.1 204 No Content GET /v1.52/containers/7d1e.../json HTTP/1.1 HTTP/1.1 200 OK
How to read it: One ApplyResourceChange (container creation) corresponds to several HTTP calls: create → connect → start → inspect; the result of inspect is written back by the provider as the new state value. Production use: Cloud providers do not need packet capture; the AWS provider, at TF_LOG_PROVIDER=DEBUG DEBUG level, prints the requests and responses directly HTTP Request Sent/HTTP Response Received (including method, URL, and status code; sensitive headers are redacted).
5. Dependency graph
terraform graph | dot -Tsvg > graph.svg # simplified resource dependencies terraform graph -type=plan | dot -Tsvg > graph-plan.svg # the real plan graph (including provider, variable, and output nodes) terraform graph -type=plan | grep -c -- '->'
Common errors:dot: command not found → apt install graphviz. Plan graphs of large stacks can have thousands of edges; use grep '"docker_container.web' to filter, or look only at the simplified graph.
Lab 1: log routing + HTTP capture + dependency graph (about 6 minutes)
cd ~/tf-lab/part7/app terraform apply -auto-approve -var web_count=1 # first scale down to 1 to free up 8081 docker run -d --name squatter -p 8081:80 nginx:1.29-alpine terraform apply -auto-approve -var web_count=2 2>&1 | tail -8
docker_container.web[1]: Creating... ╷ │ Error: Unable to start container: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint p7-web-1 (...): Bind for 0.0.0.0:8081 failed: port is already allocated │ │ with docker_container.web[1], │ on main.tf line 34, in resource "docker_container" "web": ╵
The exact wording of the error depends on the provider and Docker Engine versions. The key is “Error response from daemon”, which shows the error comes from the API layer (Docker Engine), not Terraform.
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=./m1.log terraform apply -auto-approve -var web_count=2 >/dev/null 2>&1 || true grep -n -iE 'port is already allocated|error' m1.log | head -5
Observation: the error occurs in the container start stage (create already succeeded). So Docker keeps a container in Created state, and Terraform marks it as tainted:
docker ps -a --filter name=p7-web-1 --format '{{.Names}} {{.Status}}'
terraform state list | grep web
terraform state show 'docker_container.web[1]' | head -3
p7-web-1 Created
docker_container.web[0]
docker_container.web[1]
# docker_container.web[1]: (tainted)
resource "docker_container" "web" {DOCKER_HOST=tcp://127.0.0.1:2375 terraform apply -auto-approve -var web_count=2, and in terminal A find the returned HTTP/1.1 500 POST /containers/.../start.docker rm -f squatter
terraform apply -auto-approve # the tainted web[1] will be replaced (-/+)
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8081
docker_container.web[1]: Destroying... [id=3c9a...] docker_container.web[1]: Creation complete after 1s [id=a81f...] Apply complete! Resources: 1 added, 1 changed, 1 destroyed. 200
terraform graph | dot -Tpng > graph.png && ls -l graph.png terraform graph | grep -- '->'
"docker_container.redis" -> "docker_image.redis" "docker_container.redis" -> "docker_network.lab" "docker_container.web" -> "docker_container.redis" "docker_container.web" -> "docker_image.app" "docker_container.web" -> "docker_network.lab" "docker_network.lab" -> "random_pet.suffix" "local_file.inventory" -> "docker_container.web"
Arrows mean “depends on”. web depends on redis (because env references docker_container.redis.name), so redis is created before web; destruction runs in the reverse order.
rm -f tf-*.log tf.json m1.log graph*.svg graph.png tfplan (keep the stack for Module 2).Case 1: occasional “context deadline exceeded” in CI
Problem: Two to three times a week, a plan for an AWS stack times out and fails in CI; it never reproduces locally. Approach: keep TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=$RUNNER_TEMP/tf.log enabled in CI and upload logs on failure. Analysis showed that an STS call that a aws_iam_policy_document depends on sometimes takes more than 5 seconds for DNS resolution through the corporate proxy, and the SDK keeps retrying until it times out. Configuration: fix the runner's DNS and NO_PROXY; retain the TF_LOG file for 7 days. Limitation: DEBUG logs may contain resource attributes, so the artifact needs access controls and regular deletion.
Case 2: after a provider upgrade, the same change appears in every plan
Problem: After upgrading a provider minor version, one resource shows a “permanent drift” of ~ tags = {} → null in every plan. Approach: five-step method: switching back to the old version on the same commit does not reproduce it → confirm at the layer level that the provider's ReadResource return value differs from the PlanResourceChange planned value → minimize to a single resource → find a similar issue in the provider repository, temporarily use lifecycle { ignore_changes = [tags] } and pin the old version → remove it once the fixed version is released. Limitation: ignore_changes hides real drift, so remove it promptly once the issue is fixed.
Case 3: using the dependency graph to explain “why changing one variable rebuilds half the stack”
Problem: Changing the network name variable caused 40 resources to be replaced. Approach:terraform graph -type=plan filter all paths starting from docker_network.lab , and found that every container references the network ID through networks_advanced , and that attribute is ForceNew. Configuration: during review, add “which attributes are ForceNew” to the checklist; use precondition for name-type variables to prevent accidental changes. Limitation: graph does not show attribute-level ForceNew; combine it with the # forces replacement comments in the plan.
Common errors and fixes
TF_LOG_PATH=./tf.log is set, but the file is never created
Cause: the official docs state clearly that logs are written only when TF_LOG (or TF_LOG_CORE/TF_LOG_PROVIDER) level is set.
env | grep ^TF_LOG export TF_LOG=DEBUG TF_LOG_PATH=./tf.log
Fix: set the level at the same time; note that it appends, so first : > tf.log clear the file if necessary.
Error: Failed to load plugin schemas ... Could not load the schema for provider registry.terraform.io/kreuzwerker/docker: failed to instantiate provider
Cause: core cannot start the provider subprocess: corrupted binary, architecture mismatch,/tmp mounted with noexec, antivirus blocking (Windows), or the plugin cache corrupted by concurrent writes.
TF_LOG=TRACE terraform validate 2>&1 | grep -iE 'starting plugin|plugin exited|exec format|permission denied' file .terraform/providers/registry.terraform.io/kreuzwerker/docker/*/linux_amd64/terraform-provider-docker_*
Fix:rm -rf .terraform/providers && terraform init; check TMPDIR; the plugin cache is not guaranteed to be concurrency-safe, so in CI, when multiple jobs share the cache, run init serially or use separate directories (Module 5).
Error: Error pinging Docker server: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
Cause: this is the provider failing to access the Docker API during the ConfigureProvider stage — an API/connection-layer issue: the daemon is not running, the current user is not in the docker group, or DOCKER_HOST points to the wrong address.
systemctl is-active docker; id -nG | grep -w docker; echo "DOCKER_HOST=$DOCKER_HOST" docker context ls
Fix: start the daemon,newgrp docker,unset DOCKER_HOST or explicitly set the value in the provider block host = "unix:///var/run/docker.sock".
The log file grows to several GB within minutes, filling the disk and crashing the CI runner
Cause: a large stack under TF_LOG=TRACE records every vertex traversal and the full gRPC payloads.
Fix: CI defaults to INFO; for deep investigation, use TF_LOG_CORE=WARN TF_LOG_PROVIDER=DEBUG to raise only the provider level, or combine with -target to narrow the scope only during diagnosis.
terraform graph -draw-cycles output is exactly the same as without the flag
Cause: the official docs state that -draw-cycles is only effective when used together with -type=... .
terraform graph -type=plan -draw-cycles | dot -Tsvg > cycles.svg
1. Make only the provider output DEBUG logs and core output only errors, and write them to a dated file.
TF_LOG_CORE=ERROR TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=./tf-$(date +%F-%H%M).log terraform plan
2. From the JSON logs, count how many times each gRPC method was called.
TF_LOG=JSON TF_LOG_PATH=tf.json terraform plan >/dev/null jq -r '."@message"' tf.json | grep -oE 'GRPCProvider: [A-Za-z]+' | sort | uniq -c | sort -rn
A colleague says “terraform apply reports Error: Unable to create container: ... 409 Conflict ... name is already in use” and asks you to “fix Terraform”. How do you analyze it?
“Error response from daemon / 409 Conflict” means a conflict at the API layer: a container with the same name already exists in Docker but is not in state (created manually, left over from an interrupted apply, or managed by another state). Handling: docker ps -a --filter name=... confirm the source; if this stack should manage it, use the import block or terraform import to bring it into state; if it is a leftover, delete it and retry; if it belongs to another stack, rename it to avoid the conflict. Terraform itself is not at fault.
Verified teaching videos
No dedicated video found TF_LOG covering layered logs and verifiable via oEmbed; please use the storyboard below.
Official docs
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool.
Visual: one red error line in the terminal; the camera pulls back to reveal three boxes: Core, Provider, API.
Narration: behind every Terraform error are three layers. The first troubleshooting step is to determine which layer it comes from.
Visual: TF_LOG_CORE and TF_LOG_PROVIDER are typed; log lines flow out of the left and right boxes respectively, in different colors.
Narration: TF_LOG enables both layers at once; TF_LOG_CORE and TF_LOG_PROVIDER can be set to different levels separately. Remember, setting only TF_LOG_PATH produces no logs.
Visual: a ball travels from Core via a gRPC arrow to Provider, labeled PlanResourceChange and ApplyResourceChange; then via an HTTP arrow to Docker Engine, labeled POST containers create.
Narration: core calls the provider over gRPC, and the provider in turn calls the real API. socat can print the HTTP requests on the Docker socket.
Visual: the dependency graph generated by terraform graph, with arrows highlighted one by one.
Narration: terraform graph draws resource dependencies; adding type equal to plan shows the real execution graph. Reproduce, isolate, minimize, fix, prevent regression: that is the five-step method.
Module 2 · State surgery: mv, rm, pull, push, replace-provider
- Master
state list/show/mv/rm/pull/push/replace-providerandterraform show -json, knowing for each command which part of the state it changes and that real resources are left untouched. - Understand lineage and serial:
state pushthe two safety checks, and why-forceis the last resort. - Be able to handle stale locks (
force-unlock), state corruption, and serial conflicts, and recover from MinIO/S3 object versions.
What: what is in the state file
state (format version 4) is a JSON document with these key fields:
| Field | Meaning | Notes for surgery |
|---|---|---|
version | state format version (currently 4) | do not edit by hand |
terraform_version | Terraform version that last wrote it | older CLIs may refuse to read a newer state; upgrades must be coordinated across the team |
serial | sequence number incremented on every write | must be incremented by 1 after manual edits before a push |
lineage | UUID generated when the state is first created | states with different lineage cannot overwrite each other |
outputs | root module output values | are read by terraform_remote_state other stacks |
resources[] | mode, type, name, module, provider, instances[] (index_key, attributes, dependencies, schema_version) | state mv the address fields are what you change here |
check_results | results of check blocks/conditions | — |
Why: when surgery is needed
- Refactoring: renaming resources, moving them into or out of modules, count ↔ for_each conversion, splitting/merging state (Lesson 6).
- Handover: a resource is handed to another stack or “let go” (removed from state without deleting the real resource).
- Provider source address changes (e.g., from the old
terraform-providers/dockertokreuzwerker/docker, or to a private mirror for OpenTofu). - Incidents: stale locks, state overwritten by an old version, corrupted objects, orphaned resources left by an interrupted apply.
How: imperative vs declarative
| Need | Declarative (recommended, reviewable, previewable in plan) | Imperative (modifies state immediately) |
|---|---|---|
| Change address | moved { from = ... to = ... } (1.1+) | terraform state mv |
| Let go | removed { from = ... lifecycle { destroy = false } } (1.7+) | terraform state rm |
| Bring under management | import { to = ... id = ... } (1.5+) | terraform import |
| Cross-state move | source stack removed + target stack import | state mv -state-out (local state only) or pull/edit/push |
| Change provider source | — | terraform state replace-provider |
| Force recreation | lifecycle.replace_triggered_by | terraform apply -replace=ADDR (replaces the old taint) |
lineage and serial: safety checks on state push (verified against official docs)
- different lineage → rejected: the two states are completely unrelated; overwriting may lose data.
- target serial is higher → rejected: the remote has new changes that you do not know about locally.
-forceDisabling these two checks is explicitly “not recommended” by the official docs; the target state would be overwritten directly.
When: pre-surgery checklist
- Notify the team and pause CI applies on this stack (or make sure you hold the lock).
terraform state pull > backup-$(date +%s).tfstateand confirm that versioning is enabled on the object storage.- If you can use a
moved/removed/importblock, use the block and go through PR review. - Before imperative operations, first
-dry-run(state mv,state rmsupported). - Immediately after surgery,
terraform plan, expecting No changes.
state rm will delete the resource”: it does not; it only makes Terraform forget the resource, and the real resource becomes an orphan (still billed!). ② “state mv need no code changes afterwards”: the addresses in code must be updated too, otherwise the next plan treats the new address as a create and the old one as a destroy. ③ “If the state is broken, just state push -force”: this may overwrite new data with old; restore from object versions first and compare serial. ④ “With a remote backend, the state mv will create a local backup file”: -backup options only apply to local state; for remote state, rely on state pull explicit pulls and object versioning.Structure diagram: state document and addresses
Flowchart: state push safety checks and object version recovery
Core animation: address changes before and after state surgery
The left side shows the resource addresses in state (with serial and lineage); the right side shows the Docker objects that actually exist. Click the surgery buttons below and observe what changes and what does not; then click “terraform plan” to see what Terraform plans to do when code and state are inconsistent.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
terraform state list [ADDR] | list addresses | -id=ID look up addresses from real IDs |
terraform state show ADDR | show the attributes of one instance | addresses containing [0]/["key"] need quotes |
terraform state mv SRC DST | change address | -dry-run; -state/-state-out/-backup local state only |
terraform state rm ADDR | forget a resource (does not delete it) | -dry-run; multiple addresses at once |
terraform state pull | output the current state (remote or local) to stdout | automatically upgraded to the current format; a backup is a must |
terraform state push PATH | overwrite the remote state with a file | check lineage and serial; -force skip (not recommended) |
terraform state replace-provider FROM TO | replace the provider address in state | -auto-approve,-lock-timeout |
terraform show -json | machine-readable state / plan | terraform show -json tfplan used for policy checks |
terraform force-unlock LOCK_ID | release a stale lock | use only after confirming no other process is running |
terraform apply -replace=ADDR | force recreation of one instance | replaces the old taint |
1. Back up + check lineage/serial
cd ~/tf-lab/part7/app
mkdir -p ../backups
terraform state pull > ../backups/app-$(date +%Y%m%d-%H%M%S).tfstate
terraform state pull | jq '{version, terraform_version, serial, lineage, n: (.resources|length)}'
{
"version": 4,
"terraform_version": "1.17.2",
"serial": 14,
"lineage": "6b0e3c2a-5f1d-8c47-9a3e-2d71b0c4e815",
"n": 7
}
n is the number of resource blocks (7), not the number of instances (web with count=2 counts as 1 resource and 2 instances).
2. Rename: state mv (dry-run first)
terraform state mv -dry-run docker_container.redis docker_container.cache terraform state mv docker_container.redis docker_container.cache sed -i 's/"docker_container" "redis"/"docker_container" "cache"/; s/docker_container\.redis/docker_container.cache/g' main.tf terraform plan
Would move "docker_container.redis" to "docker_container.cache" Move "docker_container.redis" to "docker_container.cache" Successfully moved 1 object(s). ... No changes. Your infrastructure matches the configuration.
Declarative equivalent (recommended; team-reviewable): rename in code and add
moved { from = docker_container.redis to = docker_container.cache }, and on the next apply Terraform migrates the address automatically; plan shows has moved to.
3. Indexed addresses and count → for_each
terraform state mv 'docker_container.web[0]' 'docker_container.web["blue"]' terraform state mv 'docker_container.web[1]' 'docker_container.web["green"]'
Brackets and quotes in addresses must be wrapped in single quotes in the shell; in Windows PowerShell, write it as 'docker_container.web[\"blue\"]'.
4. Let go: state rm and removed blocks
terraform state rm -dry-run local_file.inventory terraform state rm local_file.inventory ls inventory.txt # the file still exists
Would remove local_file.inventory Removed local_file.inventory Successfully removed 1 resource instance(s). inventory.txt
removed {
from = local_file.inventory
lifecycle {
destroy = false # removes from state only; does not delete the file
}
}
5. Replace provider source address
terraform providers # check which providers state and configuration each need terraform state replace-provider registry.terraform.io/terraform-providers/docker registry.terraform.io/kreuzwerker/docker
Terraform will perform the following actions:
~ Updating provider:
- registry.terraform.io/terraform-providers/docker
+ registry.terraform.io/kreuzwerker/docker
Changing 5 resources:
docker_container.redis
docker_container.web[0]
...
Do you want to make these changes?
Only 'yes' will be accepted to continue.
Enter a value: yes
Successfully replaced provider for 5 resources.
6. show -json: a view for scripts and policies
terraform show -json | jq -r '.values.root_module.resources[] | [.address, .provider_name, (.values.id // "-")] | @tsv'
terraform plan -out=tfplan >/dev/null && terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions != ["no-op"]) | "\(.change.actions|join(",")) \(.address)"'
docker_container.cache registry.terraform.io/kreuzwerker/docker 5e2b… docker_container.web[0] registry.terraform.io/kreuzwerker/docker a81f… ...
state pull outputs the raw state (including serial/lineage; structure is resources/instances); show -json outputs a stable display format (values.root_module, with full addresses); prefer the latter when writing scripts.
Lab 2: rename, move into a module, corruption and recovery (about 9 minutes)
cd ~/tf-lab/part7/app && ../faultbox.sh reset terraform state pull > ../backups/before-m2.tfstate terraform state pull | jq '.serial, .lineage'
mkdir -p modules/web
cat > modules/web/main.tf <<'EOF'
terraform {
required_providers {
docker = { source = "kreuzwerker/docker" }
}
}
variable "image" { type = string }
variable "network" { type = string }
variable "redis" { type = string }
variable "n" { type = number }
resource "docker_container" "web" {
count = var.n
name = "p7-web-${count.index}"
image = var.image
env = ["REDIS_HOST=${var.redis}"]
networks_advanced { name = var.network }
ports {
internal = 80
external = 8080 + count.index
}
}
output "containers" { value = docker_container.web }
EOF
In the root module, main.tf delete the resource "docker_container" "web" block, and replace it with the content below (and change local_file.inventory in docker_container.web to module.web.containers):
module "web" {
source = "./modules/web"
image = docker_image.app.image_id
network = docker_network.lab.id
redis = docker_container.redis.name
n = var.web_count
}
moved {
from = docker_container.web
to = module.web.docker_container.web
}
terraform init >/dev/null && terraform plan
# docker_container.web[0] has moved to module.web.docker_container.web[0]
resource "docker_container" "web" {
id = "a81f…"
name = "p7-web-0"
# (… unchanged attributes hidden)
}
# docker_container.web[1] has moved to module.web.docker_container.web[1]
...
Plan: 0 to add, 0 to change, 0 to destroy.
terraform apply -auto-approve && terraform state list | grep web
the moved block migrated all instances at once ([0],[1]), with no need to do them one by one state mv. After migration is complete and all environments have applied, the moved block can be kept as a historical record (for shared modules, long-term retention is recommended).
docker exec minio sh -c 'mc cat local/tfstate/part7/app.tfstate | head -c 300 > /tmp/broken && mc cp /tmp/broken local/tfstate/part7/app.tfstate' terraform plan 2>&1 | head -6
╷ │ Error: Failed to load state: Error loading state: ... unexpected end of JSON input │ ╵
docker exec minio mc ls --versions local/tfstate/part7/app.tfstate # choose the ID of the latest version before the corruption VID=$(docker exec minio mc ls --versions --json local/tfstate/part7/app.tfstate | jq -r -s 'sort_by(.lastModified) | reverse | .[1].versionId') docker exec minio mc cp --version-id "$VID" local/tfstate/part7/app.tfstate /tmp/restored.tfstate docker exec minio cat /tmp/restored.tfstate | jq '.serial, .lineage' docker exec minio mc cp /tmp/restored.tfstate local/tfstate/part7/app.tfstate terraform plan
[2026-11-15 10:41:07 UTC] 312B STANDARD 9d1c… v3 PUT app.tfstate [2026-11-15 10:38:55 UTC] 14KiB STANDARD 51ab… v2 PUT app.tfstate [2026-11-15 10:21:30 UTC] 13KiB STANDARD 0e77… v1 PUT app.tfstate 16 "6b0e3c2a-…" No changes. Your infrastructure matches the configuration.
Here the object is restored directly at the backend layer, bypassing the serial check. This is intentional: a corrupted object cannot be parsed, so Terraform cannot compare serials. Always run plan to confirm after recovery. mc ls --json The field names of the command depend on your mc version; if unsure, copy the version ID directly from the table.
terraform state push ../backups/before-m2.tfstate
Failed to write state: cannot import state with serial 14 over newer state with serial 16
Terraform refused: the backup is older than the remote; overwriting would lose the module migration results. Do not add -force.
terraform state mv module.web.docker_container.web docker_container.web (or write a reverse moved block), then ../faultbox.sh reset and terraform plan confirm No changes.Case 1: splitting a monolithic state into network and app stacks
Problem: a state with 1,200 resources takes 9 minutes to plan, and the network team and app team block each other. Approach: write an import block in the new stack to import the network resources; in the old stack, write removed { lifecycle { destroy = false } } for the same resources; merge both PRs in the same window, apply the new stack first (import), then the old stack (removal). Configuration: the old stack reads the network IDs via terraform_remote_state or a data source. Limitation: during the import, both states "own" the resources at once, so do not change those resources in that window; import blocks need the real ID of each resource, so for batches use for_each import blocks (1.7+).
Case 2: CI runner preempted, leaving a stale lock
Problem: a Spot runner was reclaimed midway through an apply, leaving .tflock in S3, and every later pipeline fails with “Error acquiring the state lock”. Approach: confirm Who/Created from the Lock Info in the error; after confirming the corresponding runner no longer exists, run terraform force-unlock LOCK_ID; then terraform plan check for half-finished resources (tainted or orphaned). Limitation: an interrupted apply may have created resources without writing state in time; compare with docker ps/ the cloud console, then import or delete manually.
Case 3: a new colleague overwrote state with a state file from an old laptop
Problem: someone, using the local state from before the migration to the remote backend, terraform.tfstate ran state push -force, and the remote lost three weeks of changes. Approach: find the version from before the overwrite in the S3 version history and restore it, then confirm with plan; afterwards, in the bucket policy allow only the CI role to PutObject, and ban -force. Limitation: if versioning was not enabled on the bucket, the only option is to import rebuild the state resource by resource; this is why Module 0 insists on enabling versioning.
Common errors and fixes
Error: Error acquiring the state lock ... Lock Info: ID: 3f2a… Path: tfstate/part7/app.tfstate Operation: OperationTypeApply Who: azureuser@lab-vm
Cause: another process is running, or an earlier process was killed with kill -9 or lost its network and left the lock behind (with use_lockfile, it is a app.tfstate.tflock object in the same directory).
ps aux | grep -v grep | grep terraform docker exec minio mc ls local/tfstate/part7/ docker exec minio mc cat local/tfstate/part7/app.tfstate.tflock
Fix: after confirming no one is running it, terraform force-unlock 3f2a…; in CI set -lock-timeout=5m to wait for normal concurrent locks instead of failing immediately.
Failed to write state: cannot import state with lineage "1a2b…" over unrelated state with lineage "6b0e…"
Cause: the file being pushed came from another stack or environment, or was created with terraform init a newly created empty state.
Fix: confirm whether the backend key and workspace are correct (terraform workspace show). If you really need to merge two states, do not push; use import/removed blocks to migrate the resources.
Error: Invalid target address ... Index brackets must contain either a literal number or a literal string.
Cause: the shell swallowed the quotes in the address, for example terraform state mv docker_container.web["blue"] ....
Fix: wrap the whole address in single quotes: 'docker_container.web["blue"]'; in PowerShell, escape the inner double quotes.
After state mv, plan shows: docker_container.cache will be created / docker_container.redis will be destroyed
Cause: only the state was changed and not the code (or vice versa). The state has the new address and the code still has the old one: Terraform sees the new address as unconfigured (destroy) and the old address as having no state (create).
Fix: make the code match the state, or undo state mv. Never apply when plan shows an unexpected destroy.
Error: Resource instance managed by newer provider version ... The current state of docker_container.web[0] was created by a newer provider version than is currently selected.
Cause: someone wrote the state with a newer provider (a higher schema_version) version, while your local lock file is still at the old version.
terraform state pull | jq '.resources[] | select(.type=="docker_container") | .instances[].schema_version' terraform init -upgrade
Fix: upgrade to the team's unified provider version (commit the updated .terraform.lock.hcl). State schema upgrades are one-way and cannot be “downgraded”.
1. Find the address in state of a Docker container, given its container ID.
terraform state list -id=$(docker inspect -f '{{.Id}}' p7-web-0)2. Count the resource instances in state that are managed by kreuzwerker/docker.
terraform show -json | jq '[.values.root_module.resources[], (.values.root_module.child_modules // [] | .[].resources[])] | map(select(.provider_name=="registry.terraform.io/kreuzwerker/docker")) | length'
You need to hand over docker_container.redis to another team's stack, with zero downtime and no recreation. Write the steps.
① Back up both sides state pull ; ② add the resource code to the target stack, plus import { to = docker_container.redis id = "<container ID>" }, plan should show 1 to import and 0 to change (adjust code first if there are differences); ③ in the source stack, remove the resource code and add removed { from = docker_container.redis lifecycle { destroy = false } }, plan should show forget rather than destroy; ④ apply the target stack first, then the source stack; ⑤ both plans show No changes; ⑥ in the source stack, change references to the resource to data sources or remote state outputs.
Verified teaching videos
No dedicated video found state mv/push covering lineage/serial and verifiable via oEmbed; please use the storyboard below.
Official docs
- State command overview
- terraform state push
- terraform state replace-provider
- Refactoring (moved blocks)
- removed block
- JSON Output Format
Video storyboard (about 100 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: state table on the left (address, ID), a Docker container icon on the right, and a line connecting them.
Narration: state remembers the binding from address to real object. All state surgery only changes this line, not the real resources.
Visual: state mv changes the address text on the left from redis to cache while the line stays connected; state rm makes the line disappear, and the container keeps running, turning grey as an “orphan”.
Narration: mv only changes the address; rm only forgets. A forgotten resource keeps running and keeps billing.
Visual: two state files labeled serial 14 and serial 16; a red prohibition sign appears on push.
Narration: push checks lineage and serial. Different lineage means an unrelated state; a lower serial means your file is stale. Do not use force.
Visual: the MinIO console's version list; select an old version, restore it, and terraform plan shows No changes.
Narration: before surgery, pull a backup and enable versioning on the object storage. If you can use moved, removed, or import blocks, do not use commands.
Module 3 · Dependency cycles, unknown values, and plan failures
- Understand that the dependency graph is a directed acyclic graph (DAG), and be able to read
Error: Cycle: A, Band useterraform graph -type=plan -draw-cycleslocate cycles, and knowcreate_before_destroythat provider configuration referencing resources can also introduce cycles. - Understand the propagation of unknown (known after apply) values , and
count/for_eachwhy they must be known at plan time; master the fix pattern “values may be unknown, keys must be known”. - Use
-targetcorrectly: only for failure recovery and two-phase bootstrapping; know the incomplete-state risk and the warnings it produces.
What: dependency graphs and unknown values
Terraform builds the dependency graph from references (appearing in expressions) and docker_container.redis.name, depends_on whose nodes are resources, data sources, providers, variables, outputs, module calls, and so on. The graph must be acyclic, because Terraform traverses it in topological order: dependencies are created first and destroyed last.
Unknown values: at plan time, computed attributes of resources not yet created (such as id,random_id.hex, or container IPs) are not yet known and show as (known after apply). Unknown values propagate along references: any expression that depends on them is also unknown.
Why: why count/for_each cannot depend on unknown values
count determines the number of instances,,for_each keys determine the instance address (local_file.per_tag["a-3f9c"]). The plan must list the address and action of every instance; if keys are only known after apply, Terraform cannot produce a complete plan, nor compare with existing instances in state, so it errors:
Error: Invalid for_each argument
on main.tf line 52, in resource "local_file" "per_tag":
52: for_each = toset(["a-${random_id.tag.hex}", "b-${random_id.tag.hex}"])
├────────────────
│ random_id.tag.hex is a string, known only after apply
The "for_each" set includes values derived from resource attributes that cannot be determined until
apply, and so Terraform cannot determine the full set of keys that will identify the instances of this
resource.
When working with unknown values in for_each, it's better to use a map value where the keys are defined
statically in your configuration and where only the values contain apply-time results.
Alternatively, you could use the -target planning option to first apply only the resources that the
for_each value depends on, and then apply a second time to fully converge.
The error message itself gives two official fix routes: static keys + unknown values (preferred), or two-phase apply with -target (for bootstrap/recovery).
How: common sources of cycles
| Source | Example | Fix |
|---|---|---|
| resources referencing each other | redis's env references the web name, and web's env references the redis name | move shared values into locals/variables (you choose the names yourself; no need to read them from resources) |
| security group / firewall rules referencing each other | two SGs reference each other in inline ingress | split into separate rule resources (aws_vpc_security_group_ingress_rule) |
create_before_destroy mixing | A has create_before_destroy (CBD), and B depends on A but does not; replacement causes a destroy/create ordering conflict | set CBD consistently on resources along the dependency chain (Terraform propagates it to dependencies automatically, but it is error-prone across modules or with explicit depends_on) |
| provider configuration referencing resources in the same stack | the provider's host comes from a cluster created in the same stack | split into two stacks (Lesson 6); 1.17.2 fixed one kind of provider reference destroy=false resources (cycle) |
| module outputs/inputs looping back | module.a's input comes from module.b's output, and b depends on a | Terraform builds the graph by value rather than by module, so most cases do not form a cycle; when one does, look -draw-cycles down to the exact value |
When: correct use of -target
- can be used: bootstrapping unknown for_each keys (create dependencies first); fixing only one resource during incident recovery; narrowing scope during investigation.
- Do not use: as a daily workflow, as a permanent fixture in CI, or to “skip” changes you don't want to deal with. It leaves state and code inconsistent for a long time, so the next person's plan will show unexpected changes.
- Terraform warns every time
Warning: Resource targeting is in effect, and warns after applyWarning: Applied changes may be incomplete, reminding you to run a full plan again.
Comparison with similar tools
| Terraform | OpenTofu | Pulumi | |
|---|---|---|---|
| unknown keys | error (deferred actions are an experimental feature, only available in alpha/experimental builds; follow the official docs) | error; 1.13 introduces new functions that help module authors reduce unknown values (see the OpenTofu docs) | expanded dynamically at apply time (the preview may be incomplete) |
| Exclude resources | only -target | -target and -exclude (1.9+) | --target/--exclude |
depends_on will solve for_each unknowns” — it will not: depends_on only affects ordering, and may even make more values unknown (data sources are deferred to apply). ② “A cycle must mean I wrote A→B→A” — it can also come from create_before_destroy replacement ordering, or from provider configuration depending on resources,-draw-cycles which the tool will draw as specific edges. ③ “-target only affects the specified resource” — it also includes the specified resource's all dependencies.Dependency graph: a normal DAG vs. the cycle after injected fault 3
Unknown-value propagation: why the “key” must be known
Interactive simulator: dependency graph topological sort and cycle detection
When Terraform traverses the dependency graph, nodes with in-degree 0 (all dependencies completed) can run in parallel, up to -parallelism at once. After ticking “inject cycle” and running, observe where the algorithm gets stuck and reports Cycle. This is a simplified illustration of Terraform's graph traversal (the real graph also contains provider, variable, and output nodes, and performs cycle detection before traversal).
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
terraform graph -type=plan -draw-cycles | highlight cycles in color on the graph | output DOT, rendered with dot -Tsvg to render |
terraform validate | Static check | most cycles can be detected in the validate phase |
terraform console | evaluate expressions, inspect types | type(local.x), check whether keys are known |
terraform plan -target=ADDR | plan only the specified resource and its dependencies | can be repeated multiple times; module address -target=module.web |
terraform apply -target=ADDR | step one of two-phase bootstrap | a full apply must be run afterwards |
terraform plan -refresh-only | only syncs state with the real world | unrelated to unknown values in this module, but often used together to rule out drift interference |
1. Reproduce and locate the cycle
cd ~/tf-lab/part7/app && ../faultbox.sh inject 3 terraform validate
╷ │ Error: Cycle: docker_container.web, docker_container.redis │ ╵
terraform graph -type=plan -draw-cycles | dot -Tsvg > cycle.svg grep -n 'docker_container.web\[0\].name\|docker_container.redis.name' main.tf
In the SVG, the edges that form the cycle are highlighted in color. Common errors: Without -type set, -draw-cycles it has no effect. Real-project cycles are often long (A→B→C→D→A), and the error lists all nodes on the cycle.
2. Fix: move constants into locals
locals {
redis_name = "p7-redis"
web_names = [for i in range(var.web_count) : "p7-web-${i}"]
}
resource "docker_container" "redis" {
name = local.redis_name
env = ["WEB=${local.web_names[0]}"] # no longer references resource attributes
# ...
}
resource "docker_container" "web" {
count = var.web_count
name = local.web_names[count.index]
env = ["REDIS_HOST=${local.redis_name}"]
# ...
}
Note: this also removes the implicit web → redis dependency. If redis really must start first, use depends_on = [docker_container.redis] an explicit depends_on to keep a one-way dependency.
3. Reproduce the unknown key and fix it with static keys
../faultbox.sh reset && ../faultbox.sh inject 4 terraform plan 2>&1 | grep -A2 'Error:'
resource "local_file" "per_tag" {
for_each = {
a = "a-${random_id.tag.hex}"
b = "b-${random_id.tag.hex}"
}
filename = "${path.module}/${each.value}.txt"
content = each.value
}
terraform plan | grep -E '^\s+# local_file.per_tag'
# local_file.per_tag["a"] will be created # local_file.per_tag["b"] will be created
4. When the code cannot be changed: two-phase apply with -target
terraform apply -target=random_id.tag -auto-approve terraform apply -auto-approve # phase two: random_id.tag.hex is already in state, so the key is known
╷ │ Warning: Resource targeting is in effect │ │ You are creating a plan with the -target option, which means that the result of this plan may not │ represent all of the changes requested by the current configuration. ... │ Warning: Applied changes may be incomplete ... Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Production use: Use only for the initial bootstrap; afterwards the keys are determined by values in state, but if random_id is replaced, the problem will recur — which is exactly why the “static keys” approach is better.
Lab 3: three kinds of plan failure (about 8 minutes)
../faultbox.sh reset && ../faultbox.sh inject 3, run terraform validate, use -draw-cycles to draw the graph; following step 2 of the Commands tab, fix it with locals and confirm terraform plan that only redis's env changes (-/+ replacement, since changes to docker_container's env force replacement).
terraform plan | grep -E 'must be replaced|forces replacement|Plan:'
# docker_container.redis must be replaced
~ env = [ # forces replacement
Plan: 1 to add, 0 to change, 1 to destroy.
When you see “replace”, stop and think: this replacement will cause a brief redis outage. It is acceptable in the lab; in production it must be evaluated. Once done, ../faultbox.sh reset, do not apply.
../faultbox.sh inject 4, reproduce Invalid for_each argument, fix it with static map keys,terraform apply -auto-approve, and confirm that it generates a-xxxx.txt and b-xxxx.txt.resource "local_file" "maybe" {
count = length(docker_container.web[0].network_data) > 0 ? 1 : 0
filename = "${path.module}/maybe.txt"
content = "ok"
}
Since web[0] already exists in state,network_data is known at plan time and no error occurs; but if you also change web_count from 0 to 1 (web[0] not yet created), you will get Error: Invalid count argument ... The "count" value depends on resource attributes that cannot be determined until apply. Use terraform plan -var web_count=0 scale down first, then -var web_count=1 try it, and appreciate that “the same code may error or not depending on the state”.
sed -i 's/length = 2/length = 3/' main.tf # modify random_pet (this also replaces the network and containers) terraform plan -target=local_file.inventory | grep -E 'Plan:|will be|must be'
Observe: even if you target only one file, the plan includes replacements of random_pet, the network, and all containers on its dependency chain. -target includes dependencies. Revert the change: git checkout main.tf.
../faultbox.sh reset; rm -f a-*.txt b-*.txt maybe.txt cycle.svg; terraform apply -auto-approve (back to baseline; expect random_id/per_tag to be destroyed).Case 1: for_each iterating over the IDs of newly created subnets
Problem:for_each = toset(aws_subnet.private[*].id) On the first plan in a brand-new environment it reports Invalid for_each argument, while existing environments work fine. Approach: Switch to using the subnets' logical names (var.subnets map keys, such as app-a,app-b) as the for_each keys, with values being aws_subnet.private[each.key].id. Limitation: changing keys changes instance addresses, so you need moved blocks to move old addresses (by ID) to new ones (by logical name).
Case 2: two security groups referencing each other
Problem: The app SG allows traffic from the lb SG, and the lb SG's egress references the app SG again; the inline rules form a cycle. Approach: Both SGs keep only empty shells, and the rules are split into aws_vpc_security_group_ingress_rule/egress_rule separate resources that depend on both SGs, but the SGs no longer depend on each other. Limitation: Inline rules and separate rule resources must not be mixed, or they will overwrite each other.
Case 3: using -target to fix a single resource during an incident
Problem: In a large stack, a load balancer listener was misconfigured and caused 5xx errors in production, but the main branch also contains other unreviewed changes. Approach: Modify the listener on the incident branch,terraform apply -target=module.lb.aws_lb_listener.https fixing only that; after the incident, merge the main branch and run a full plan to check for drift. Limitation: Record in the incident log that -target was used, and schedule a follow-up full apply.
Common errors and fixes
Error: Cycle: docker_container.web, docker_container.redis
Cause: mutual references. Diagnosis:terraform graph -type=plan -draw-cycles | dot -Tsvg > c.svg, search the code for references each resource makes to the other's attributes.
Fix: Move constants that both sides need into locals/variables; split rule resources; split the stack if necessary.
Error: Cycle: module.app.aws_instance.x (destroy deposed 3f1b...), module.app.aws_instance.x, ... (create_before_destroy related)
Cause: During replacement, the ordering of create_before_destroy conflicts with resources that depend on it; the node name carries (destroy)/deposed.
Fix: Set consistently along the dependency chain: lifecycle { create_before_destroy = true }; remove unnecessary depends_on; apply in two steps (replace upstream first, then handle downstream).
Error: Invalid for_each argument ... cannot determine the full set of keys that will identify the instances of this resource.
Fix: static keys + unknown values; or -target two-phase; do not use depends_on as a “fix”. Use terraform console to inspect expressions: known values are shown directly, and unknown values show (known after apply).
Error: Invalid count argument ... The "count" value depends on resource attributes that cannot be determined until apply
Cause: Same as above: count depends on an unknown value (for example length(aws_instance.x[*].id)).
Fix: Control the count with a variable (count = var.n), rather than deriving the count from the results of other resources.
Warning: Resource targeting is in effect … the next full plan shows many unexpected changes
Cause: A -target apply was run earlier without a following full apply, so other code changes have never been applied.
Fix: Review the full plan carefully before applying; forbid -target in CI (you can check arguments in a wrapper script).
1. Generate a dependency graph SVG that highlights the cycle.
terraform graph -type=plan -draw-cycles | dot -Tsvg > cycles.svg
2. Create only random_id.tag and its dependencies, then fully converge.
terraform apply -target=random_id.tag -auto-approve && terraform apply -auto-approve
A module accepts var.instance_ids (an output from another module), and internally for_each = toset(var.instance_ids). The first deployment to a new environment fails, while existing environments work. How should the interface be redesigned?
The failure happens because IDs are unknown at plan time in the new environment. Change the interface so that map(string) keys are static logical names defined by the caller (such as web-a), with IDs as values; inside the module, for_each = var.instances. This makes the instance addresses ["web-a"], known at plan time. Existing environments need moved blocks to move the old keys (IDs) to the new keys (logical names).
Verified teaching videos
No dedicated video covering cycles and unknown values that can be verified via oEmbed was found; please use the storyboard below.
Official docs
- for_each meta-argument (including limitations)
- plan -target
- lifecycle (create_before_destroy)
- terraform graph
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: arrows drawn between resource blocks, lighting up one by one in topological order.
Narration: a reference is an edge in the dependency graph. Terraform traverses in topological order: dependencies are created first and destroyed last.
Visual: two-way red arrows appear between redis and web; traversal stops and an Error Cycle pops up.
Narration: two resources referencing each other form a cycle. Put the constant both sides need into locals, and the cycle is broken.
Visual: for_each keys show as question marks with “known after apply” beside them; after switching to static keys a and b, the question marks appear only on the values.
Narration: plan must know the address of every instance. Values may be unknown; keys must be known.
Visual: -target lights up only one resource and its upstream dependencies, and a yellow warning bar appears.
Narration: -target is a first-aid tool, not a daily workflow. Always run a full apply afterwards.
Module 4 · Provider issues and API throttling
- Understand API throttling (HTTP 429 / Throttling) and provider retry backoff; know the AWS provider's
max_retries(default 25),retry_mode, and the effect of lowering-parallelism. - Be able to use resource-level
timeoutsblocks (create/update/delete) and distinguish “provider wait timeout” from “API error”. - Identify eventual consistency issues (IAM propagation, DNS, resources just created but not yet readable) and provider bugs (
Provider produced inconsistent result after apply, plugin panics), and write a proper provider issue.
What: what the provider does in front of the API
A ApplyResourceChange is usually not a single HTTP request, but: start creation → poll and wait until the resource reaches the target state (waiter) → read back full attributes → return the new state to core. Meanwhile, the provider's SDK automatically retries retryable errors (429, 5xx, certain 409/400 error codes, network errors) and uses exponential backoff + jitter.
| Mechanism | Controlled by | Typical configuration |
|---|---|---|
| SDK-level retries | provider + cloud SDK | AWS: provider parameter max_retries (default 25),retry_mode (standard/adaptive; can also use AWS_RETRY_MODE); azurerm: built into the SDK, no corresponding parameter (see the docs) |
| resource waiter timeout | timeouts in the resource schema timeouts block | timeouts { create = "60m" update = "30m" delete = "45m" }, usable only for resources and operations documented as supported |
| concurrency | Terraform core | -parallelism=N (default 10): at most N graph nodes execute at the same time |
| health wait | resource parameter | docker_container's wait + wait_timeout (seconds, default 60; the container must define a healthcheck) |
Why: different signals for three kinds of problems
| Type | Typical error / log | Handling direction |
|---|---|---|
| API throttling | many 429/ThrottlingException/Rate exceeded in DEBUG logs, followed by success or “exceeded max retries” | lower concurrency, raise the retry count, request quota, stagger, split stacks |
| wait timeout | timeout while waiting for state to become 'available',context deadline exceeded | first confirm whether the resource actually succeeded in the cloud; reasonably increase timeouts; check cloud events |
| eventual consistency | a newly created IAM role “cannot be assumed”, a newly created resource NotFound; retrying once is enough | upgrade the provider (most already have retries built in); temporarily use time_sleep; do not use depends_on in place of |
| Provider bug | Provider produced inconsistent result after apply,Provider produced inconsistent final plan,The terraform-provider-xxx plugin crashed! | the error text already states “This is a bug in the provider”; collect logs, make a minimal reproduction, search for existing issues, file an issue, and temporarily pin the version |
How: core's consistency check
After apply, core compares the new values returned by the provider with the planned values: attributes known at plan time must not change after apply, and unknown attributes must become known with the correct type. If not, it reports inconsistent result after apply— this is core protecting you; the problem lies in the provider implementation (or the API returned a normalized value that the provider did not handle).
When: what to adjust and by how much
- Creating large batches of the same kind of resource (hundreds of DNS records, IAM policies) → first reduce
-parallelismto 3–5, then consider raising retries. - Slow resources such as databases and Kubernetes clusters → set the timeout to 1.5–2× the official typical creation time
timeouts. - The CI total timeout must be greater than the longest Terraform resource timeout; otherwise the runner is killed first, leaving stale locks and intermediate state.
Comparison with similar tools
| Terraform | Ansible | ARM/Bicep, CloudFormation | |
|---|---|---|---|
| Retries | built into provider/SDK | built into modules + retries/until | server-side orchestration, handled automatically |
| Timeouts | timeouts block | async/poll | server-side; stack-level timeout |
| Eventual consistency | handled by the provider; occasionally needs time_sleep | pause/wait_for | handled server-side; users rarely notice |
max_retries to 100 avoids throttling” — it only makes failures come later; the real fix is lower concurrency or a higher quota. ③ “inconsistent result means my configuration is wrong” — the error text clearly says it is a provider bug, but it can be worked around by adjusting the configuration (for example, using the API-normalized value).Sequence diagram: retries and waits inside one ApplyResourceChange
Decision diagram: attributing provider errors
Interactive simulator: API throttling and exponential backoff
Simulates creating 60 resources of the same kind (e.g., DNS records). The API uses token-bucket throttling: R tokens are replenished per second, and excess requests return 429. On 429 the provider retries with “exponential backoff + full jitter”; beyond max_retries the resource fails. Adjust the parameters and observe total time and failure count — this is a simplified illustration of retry strategies such as the AWS SDK's.
Core commands and configuration
| Command / configuration | Purpose | Notes |
|---|---|---|
terraform apply -parallelism=3 | lower concurrency | the most direct mitigation for throttling |
timeouts { create = "10m" } | resource waiter limit | only effective for resources that list Timeouts in the docs; format like "30s","10m","2h" |
provider "aws" { max_retries = 10 } | SDK retry count | default 25; retry_mode = "adaptive" will proactively throttle on the client side |
resource "time_sleep" | artificial wait (hashicorp/time) | create_duration = "30s", a last resort |
terraform apply -replace=ADDR | rebuild tainted/abnormal instances | use when the resource state is uncertain after a timeout |
terraform version + TF_LOG=TRACE | collect information for an issue | attach a minimal reproduction configuration and a redacted log gist |
1. docker_container health wait and timeouts
resource "docker_container" "slow" {
name = "p7-slow"
image = docker_image.app.image_id
healthcheck {
test = ["CMD-SHELL", "test -f /tmp/ready"] # deliberately never healthy
interval = "2s"
retries = 3
start_period = "1s"
}
wait = true
wait_timeout = 15 # seconds, default 60
timeouts {
create = "2m"
}
}
time terraform apply -auto-approve -target=docker_container.slow 2>&1 | tail -6
docker_container.slow: Still creating... [10s elapsed] ╷ │ Error: container p7-slow failed to be in healthy state ... │ │ with docker_container.slow, ╵ real 0m17.402s
How to verify:docker inspect -f '{{.State.Health.Status}}' p7-slow shows unhealthy; the container has actually been created. Check terraform state list to determine whether it entered state (and whether it is tainted), then decide whether to fix the health check and then -replace, or delete it manually.
2. AWS provider retry configuration (reference only; not executed in this lab)
provider "aws" {
region = "ca-central-1"
max_retries = 10 # default 25; lower exposes problems sooner, higher absorbs transient throttling
retry_mode = "adaptive" # client-side token bucket, actively slows down
}
3. Count 429s from DEBUG logs (AWS scenario)
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=aws.log terraform apply -parallelism=20 grep -cE 'http.response.status_code=429|ThrottlingException|Rate exceeded' aws.log grep -E 'HTTP Request Sent' aws.log | grep -oE 'rpc.method=[A-Za-z]+' | sort | uniq -c | sort -rn | head
Log field names (such as http.response.status_code,rpc.method) change with provider/SDK versions; first use grep -m3 'HTTP Request Sent' aws.log to look at one line's actual format before writing the filter.
4. Temporary workaround for eventual consistency
resource "aws_iam_role" "fn" { /* ... */ }
resource "time_sleep" "iam_propagation" {
depends_on = [aws_iam_role.fn]
create_duration = "20s"
}
resource "aws_lambda_function" "fn" {
role = aws_iam_role.fn.arn
depends_on = [time_sleep.iam_propagation]
# ...
}
Production use: first check whether the newer provider version already has retries built in (most common scenarios are covered); time_sleep makes every replacement wait longer, and does not guarantee enough time.
Lab 4: reproducing timeouts, orphans, and “provider inconsistency” (about 7 minutes)
health.tf from step 1 of the Commands tab into ~/tf-lab/part7/app, run terraform apply -target=docker_container.slow -auto-approve, and observe that it fails after about 15 seconds.
docker ps -a --filter name=p7-slow --format '{{.Names}} {{.Status}}'
terraform state list | grep slow || echo "not in state (orphan)"
Record the result: does the container exist, and is it in state? Is it marked tainted? (Different provider versions may handle “created successfully but the wait failed” differently; that is why you must verify it yourself.)
["CMD-SHELL", "wget -qO- http://127.0.0.1/ >/dev/null || exit 1"] (the nginx image contains busybox wget), then:
docker rm -f p7-slow 2>/dev/null; terraform apply -auto-approve -target=docker_container.slow
docker inspect -f '{{.State.Health.Status}}' p7-slow
docker_container.slow: Creation complete after 4s [id=…] healthy
If the container is already in state and tainted, directly terraform apply will replace it automatically; if it is not in state but a container with the same name exists in Docker, Conflict ... name is already in use will appear, and you must delete it or import it first.
docker update --restart=always p7-web-0 terraform plan | grep -B2 -A2 restart
# docker_container.web[0] will be updated in-place
~ resource "docker_container" "web" {
~ restart = "always" -> "no"
This is drift (the real world was changed), not a provider bug: refresh read always, but the configuration requires no. A provider bug is characterized by right after apply finishes an inconsistent result being reported, or the same change still showing up in a plan run immediately after apply (permanent drift).
### Terraform and provider versions
$ terraform version
Terraform v1.17.2 on linux_amd64
+ provider registry.terraform.io/kreuzwerker/docker v4.7.0
### Affected resource
docker_container (wait = true)
### Minimal configuration
(paste health.tf, delete unrelated resources)
### Expected behavior / Actual behavior
### Steps to reproduce
1. terraform apply
### Debug output
gist link for TF_LOG=DEBUG (redacted)
### Docker Engine version
docker version --format '{{.Server.Version}}'rm health.tf && terraform apply -auto-approve (destroy slow; change web[0]'s restart back to no).Case 1: batch creation of 400 Route 53 records gets throttled
Problem: With default concurrency of 10, many Throttling: Rate exceeded, apply takes over 40 minutes and occasionally fails. Approach: lower it to -parallelism=4, and total time actually drops to 12 minutes (retries and backoff are greatly reduced); split the frequently changing records into a separate stack. Configuration: in the pipeline, pin TF_CLI_ARGS_apply="-parallelism=4" for this stack. Limitation:TF_CLI_ARGS_* this affects every place that calls the command; remember to document it in the README.
Case 2: Azure database creation times out but the resource already exists
Problem: apply reports “context deadline exceeded”, and a re-run reports that the resource already exists (import needed). Approach: confirm in the portal that the resource actually succeeded; set the timeout to the default listed for that resource in the azurerm docs timeouts { create = "90m" }; use an import block to bring the existing resource into state. Limitation: azurerm explicitly errors and requires an import when a resource exists but is not in state; this is a safeguard against accidental management, so do not disable it.
Case 3: inconsistent result after a provider upgrade
Problem: after upgrading a provider minor version, creating a resource reports produced an unexpected new value: .tags_all: inconsistent values for sensitive attribute. Approach: find a similar issue in the provider repository and roll back to the previous version (change the constraint + init -upgrade + commit the lock file), and subscribe to the issue; after the fixed version is released, upgrade and verify in staging. Limitation: a failed apply may already have created resources; after rolling back, run plan first to check whether an import or -replace is needed.
Common errors and fixes
Error: Provider produced inconsistent result after apply ... produced an unexpected new value: .xxx: was cty.StringVal("a"), but now cty.StringVal("A"). This is a bug in the provider, which should be reported in the provider's own issue tracker.
Cause: the API normalized values (case, JSON key order, defaults) and the provider did not handle them before returning.
Fix: temporarily write the configuration in the API-normalized form; search and file an issue; pin a version without this problem if necessary. The resource may already have been created, so first terraform plan check whether it is in state (usually marked tainted).
Error: Provider produced inconsistent final plan ... When expanding the plan for X to include new values learned so far during apply, provider produced an invalid new value
Cause: during re-planning in the apply phase, the values returned by the provider are incompatible with those from the plan phase, usually related to unknown values and computed attributes.
Fix: the error text itself points to a provider bug. You can try a two-step apply (create the upstream first so the values become known); upgrade the provider; attach TRACE logs and file an issue.
Error: The terraform-provider-docker_v4.7.0 plugin crashed! ... panic: runtime error: invalid memory address or nil pointer dereference
Cause: the provider code panicked. Terraform prints a stack trace and suggests reporting it to the provider maintainers.
TF_LOG=TRACE TF_LOG_PATH=crash.log terraform apply grep -n 'panic:' -A30 crash.log | head -40
Fix: file an issue (attach the stack trace, a minimal reproduction, and the version); find the combination of configuration that triggers the panic and avoid it; roll back the version.
Error: waiting for ... create: timeout while waiting for state to become 'available' (last state: 'creating', timeout: 40m0s)
Cause: the resource waiter timed out; the cloud may still be creating the resource.
Fix: check the actual state in the cloud console or CLI; if the resource eventually succeeds, the next plan decides the action based on whether the resource is in state (tainted → replace; not in state → import needed); increase timeouts as needed.
Error: ... operation error ...: exceeded maximum number of attempts, 25, https response error StatusCode: 400, ... api error ThrottlingException: Rate exceeded
Cause: the AWS SDK retried 25 times (the default max_retries) and was still throttled.
Fix:-parallelism=3; retry_mode = "adaptive"; check whether other systems (another pipeline, automation scripts) call the same API at the same time; request a higher quota.
1. Run apply with concurrency 3, and write the provider's DEBUG logs to a file to count 429s.
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=apply.log terraform apply -parallelism=3 grep -c '429' apply.log
2. Force replacement of a container instance whose state is abnormal.
terraform apply -replace='docker_container.web[0]'
During creation of a Kubernetes cluster, apply reports a timeout (40m); the CI job is then canceled because the total duration exceeded 45 minutes. The next day a re-run reports “already exists”. Reconstruct the incident and propose improvements.
Reconstruction: when the 40-minute waiter timed out, the cloud was still creating the cluster; the 45-minute CI limit was too tight, so the job may have been killed while Terraform was still writing state or releasing the lock, leaving no cluster in state or a stale lock. The cluster was eventually created and became an orphan, causing a conflict the next day. Improvements: ① first force-unlock (if there is a stale lock), and use an import block to bring the cluster into state; ② set timeouts { create = "90m" }, with the CI timeout greater than the slowest resource timeout plus a margin; ③ split slow resources into a separate stack; ④ in alerts, distinguish “Terraform failure” from “cloud-side failure”.
Verified teaching videos
No dedicated video verifiable via oEmbed was found that covers Terraform provider retries, timeouts, and provider bug reporting. For reference, see the comprehensive course:
Official docs
- Operation Timeouts
- AWS provider: max_retries / retry_mode
- docker_container (wait, wait_timeout, timeouts)
- time_sleep
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: ten requests rush at one API gate; the counter on the gate shows five per second; the rest bounce back with 429.
Narration: cloud APIs all have rate limits. The higher the concurrency, the more requests get rejected.
Visual: rejected requests wait one, two, and four seconds before retrying, with random jitter on the timeline.
Narration: the provider retries automatically with exponential backoff plus jitter; an error is reported only after retries are used up. Lowering parallelism is often more effective than raising retries.
Visual: a database icon spins in the “creating” state; the timer reaches the timeouts limit and turns red.
Narration: the timeouts block limits the wait time. A timeout does not mean failure; the resource may already have been created, so check the cloud first.
Visual: the error Provider produced inconsistent result appears, with “This is a bug in the provider” highlighted below; switch to the GitHub issue template.
Narration: this kind of error is a provider bug. Collect the version, a minimal configuration, and logs; search and file an issue; temporarily pin a working version.
Module 5 · Performance: parallelism, refresh, and large stacks
- Split one run into init / refresh / plan calculation / apply four stages, and use
timeandterraform apply -jsonto measureelapsed_secondsthe time spent on each resource. - Master
-parallelism,-refresh=false,-minimal-refresh(1.17),-refresh-only— applicable scenarios and risks. - Configure the provider plugin cache (
plugin_cache_dir/TF_PLUGIN_CACHE_DIR), understand its relationship with the lock file, and know when a large stack should be split.
What: where the time goes
| Phase | Main cost | Relation to resource count | Main optimization |
|---|---|---|---|
| init | downloading providers (the AWS provider archive is hundreds of MB), downloading modules, initializing the backend | scales with the number of providers/modules | plugin cache, network mirror (provider_installation), CI cache .terraform |
| refresh | calling ReadResource on each resource in state (usually 1–N API calls each), and data source reads | grows linearly, bounded by API throttling | -minimal-refresh,-refresh=false, splitting stacks, reducing data sources |
| plan calculation | expression evaluation,PlanResourceChange, large for expressions | usually small; huge locals or nested modules can slow it significantly | simplify expressions, reduce module nesting |
| apply | real API calls and waits | bounded by the length of the dependency chain (critical path) and concurrency | -parallelism, reduce unnecessary depends_on |
| state reads/writes | downloading/uploading the whole state, locking | the bigger the state, the slower (noticeable at tens of MB) | splitting stacks |
Why: large stacks have more problems than just slowness
A state with thousands of resources must refresh every resource on each plan, easily hitting API throttling; the blast radius of a change is large; lock contention is frequent (teammates wait for each other); plan output becomes too long to review. So the end point of performance optimization is usually architectural change (Lesson 6's state splitting), not parameter tuning.
How: several key parameters (verified 2026-11)
| Parameter | Meaning | Risk |
|---|---|---|
-parallelism=N | Upper limit on graph nodes executed concurrently, default 10. Applies to both plan and apply | too high → throttling / local resource exhaustion; too low → resources off the critical path also queue |
-refresh=false | Skip refresh and plan using the values in state directly | drift is not visible; may produce wrong plans based on stale information |
-minimal-refresh (new in 1.17.0) | refresh only resources that have proposed changes (the original intent per the official CHANGELOG) | drift in unchanged resources is not detected; combine with regular plan -refresh-only drift detection (Lesson 5) |
-refresh-only | refresh only, producing a plan that “syncs state to reality” | after apply it writes drift into state (accepts reality), so review first |
-target | narrow scope | see Module 3; not used for performance optimization |
provider plugin cache (CLI configuration file, verified in official docs)
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"(set in~/.terraformrc, on Windows it is%APPDATA%\terraform.rc, using forward slashes in the path) or the environment variableTF_PLUGIN_CACHE_DIR.- The directory must exist in advance; Terraform does not create it automatically. Terraform also never deletes old versions from the cache, so clean up regularly.
- By default, a cached package is used only if its checksum matches an entry in the lock file;
plugin_cache_may_break_dependency_lock_filecan be relaxed, but the official docs recommend that most users not set it. - the cache directory is not guaranteed to be concurrency-safe: multiple
terraform initwriting to the same cache at once has undefined behavior.
When: optimization order
- Measure:
timeeach phase;apply -jsonfind the slowest resources. - slow init → plugin cache / CI cache / internal mirror.
- slow refresh → use
-minimal-refreshin the PR pipeline, and a full refresh for nightly drift detection; reduce unnecessary data sources. - slow apply → look at the critical path; raise parallelism until throttling appears; split slow resources into their own stack.
- large state, heavy team conflicts → split the stack.
Comparison with similar tools
| Terraform 1.17 | OpenTofu 1.13 | Pulumi | |
|---|---|---|---|
| concurrency | -parallelism (default 10) | same | --parallel |
| skip refresh | -refresh=false,-minimal-refresh | -refresh=false (whether minimal-refresh exists is per the OpenTofu docs) | does not refresh by default,--refresh enable |
| plugin cache | plugin_cache_dir | same-named configuration, compatible with | plugin directory shared globally |
-refresh=false is just faster, with no side effects” — if someone manually deleted a resource, plan will not propose recreating it. ③ “The plugin cache can share the same NFS directory across multiple CI jobs” — the official docs explicitly do not guarantee concurrency safety; use an independent cache per job or serialize initialization, and restore the directory using the CI's cache mechanism.Gantt chart: concurrency and the critical path
Comparison chart: number of ReadResource calls for three refresh strategies
Interactive timer: parallelism, refresh strategy, and plugin cache
Simulates the execution of a stack with N resources terraform init && terraform plan (only k resources have proposed changes). Each ReadResource needs 1 API call (200 ms), and the API quota is Q req/s; init downloading providers takes D seconds (about 0.5 seconds on a cache hit). The values are illustrative, to help understand which phase each parameter affects.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
time terraform plan | rough measurement of total time | measure init, plan, and apply separately |
terraform apply -json | machine-readable UI event stream | apply_complete with hook.elapsed_seconds; refresh_start/refresh_complete with timestamps |
terraform plan -parallelism=20 | adjust concurrency | default 10 |
terraform plan -minimal-refresh | refresh only resources with proposed changes | 1.17.0+ |
terraform plan -refresh=false | skip refresh entirely | suitable for emergencies or when there is known to be no drift |
TF_PLUGIN_CACHE_DIR | enable plugin cache | directory must be created in advance |
TF_CLI_ARGS_plan="-parallelism=20" | attach default arguments to a subcommand | set uniformly in CI |
1. Enable the plugin cache and compare init times
mkdir -p ~/.terraform.d/plugin-cache cat >> ~/.terraformrc <<'EOF' plugin_cache_dir = "$HOME/.terraform.d/plugin-cache" EOF cd ~/tf-lab/part7/app rm -rf .terraform/providers && time terraform init >/dev/null # first run: download and write to cache rm -rf .terraform/providers && time terraform init >/dev/null # second run: link from cache ls ~/.terraform.d/plugin-cache/registry.terraform.io/*/
real 0m6.912s real 0m1.204s docker external local random
2. Use apply -json to find the slowest resources
terraform apply -auto-approve -json -replace='docker_container.web[0]' \ | jq -r 'select(.type=="apply_complete") | [.hook.elapsed_seconds, .hook.resource.addr, .hook.action] | @tsv' \ | sort -rn | head
1 docker_container.web[0] create 0 local_file.inventory update 0 docker_container.web[0] delete
3. Compare refresh strategies
for opt in "" "-minimal-refresh" "-refresh=false"; do /usr/bin/time -f "%e s plan $opt" terraform plan $opt -lock=false >/dev/null done
-lock=false Use only in read-only benchmarks, so lock overhead does not interfere; do not disable locking for a formal plan. Common errors: An older CLI does not recognize -minimal-refresh (it reports flag provided but not defined); check that terraform version is ≥ 1.17.0.
4. Measure the time each resource takes in the refresh phase
terraform plan -json | jq -r 'select(.type=="refresh_start" or .type=="refresh_complete") | [."@timestamp", .type, .hook.resource.addr] | @tsv' | head
Lab 5: 50-resource benchmark and optimization report (about 8 minutes)
mkdir -p ~/tf-lab/part7/bench && cd ~/tf-lab/part7/bench
cat > main.tf <<'EOF'
terraform {
required_providers {
docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
}
}
provider "docker" {}
variable "n" { default = 50 }
resource "docker_image" "bb" {
name = "busybox:1.37"
keep_locally = true
}
resource "docker_container" "c" {
count = var.n
name = "p7-bench-${count.index}"
image = docker_image.bb.image_id
command = ["sleep", "86400"]
memory = 16
}
EOF
terraform init >/dev/null
/usr/bin/time -f "apply %e s" terraform apply -auto-approve >/dev/nullfor p in 1 5 10 25; do terraform destroy -auto-approve >/dev/null /usr/bin/time -f "parallelism=$p apply %e s" terraform apply -auto-approve -parallelism=$p >/dev/null done
parallelism=1 apply 41.37 s parallelism=5 apply 10.02 s parallelism=10 apply 6.11 s parallelism=25 apply 5.48 s
Local Docker has no API throttling; the benefit diminishes after about 10 (limited by dockerd's own concurrency and disk I/O). On cloud APIs the curve gets worse after the throttling point.
docker rm -f p7-bench-7 for opt in "" "-minimal-refresh" "-refresh=false"; do echo "== plan $opt"; /usr/bin/time -f "%e s" terraform plan $opt -lock=false 2>&1 | grep -E 'Plan:|No changes|^[0-9.]+ s' done
== plan Plan: 1 to add, 0 to change, 0 to destroy. 1.92 s == plan -minimal-refresh No changes. Your infrastructure matches the configuration. 0.88 s == plan -refresh=false No changes. Your infrastructure matches the configuration. 0.71 s
Key observation: the last two are faster, but did not detect the deleted p7-bench-7. This is -minimal-refresh/-refresh=false why a periodic full refresh must be combined with them. (The output is illustrative; use your actual results. If the minimal-refresh behavior in your 1.17 version differs, record it in your report.)
## Performance optimization report: part7/bench (N=50) | Scenario | Time | Notes | |---|---|---| | init (no cache / with cache) | 6.9 s / 1.2 s | plugin_cache_dir | | apply parallelism 1/5/10/25 | … | gains diminish after 10 | | plan full / minimal / refresh=false | … | the last two cannot see drift | ### Recommendations 1. Enable the plugin cache in CI (independent directory per job + CI cache restore) 2. Use -minimal-refresh for PR plans; nightly plan -refresh-only -detailed-exitcode for drift detection 3. Keep parallelism at 10; tune cloud stacks based on 429 statistics 4. When state exceeds N resources or plan takes > 5 minutes, split the stack by change frequency
terraform destroy -auto-approve && cd .. && rm -rf bench.Case 1: PR plan drops from 11 minutes to 2 minutes
Problem: a platform stack with 1,800 resources takes 11 minutes per PR plan, 9 of which are spent on refresh. Approach: upgrade to 1.17 and switch the PR pipeline to -minimal-refresh; keep a full plan -refresh-only -detailed-exitcode every night, and open a ticket if drift is found; in the medium term, split IAM and networking into separate stacks. Limitation: a plan before merge may not show drift that happened that day; the apply pipeline keeps a full refresh.
Case 2: CI init downloads 600 MB every time
Problem: 30 stacks × over a hundred pipeline runs per day; provider downloads consume a lot of bandwidth and occasionally fail. Approach: set TF_PLUGIN_CACHE_DIR=$CI_PROJECT_DIR/.tf-plugin-cache for each job and restore it with the CI cache keyed by lock file hash; the long-term solution is an internal provider network mirror (provider_installation { network_mirror { url = ... } }). Limitation: the lock file must include hashes for all runner platforms (terraform providers lock -platform=..., Module 6), otherwise even cache hits will re-download because verification fails.
Case 3: apply slows down after raising parallelism
Problem: to speed things up, parallelism was set to 50, and on Azure the apply went from 20 minutes to 35 minutes. Approach: DEBUG logs showed many 429s and Retry-After; rolled back to 10, and split the many similar role assignments into batches. Limitation: limits differ across clouds and services; there is no universal best value, so you must measure.
Common errors and fixes
flag provided but not defined: -minimal-refresh
Cause: the CLI version is below 1.17.0 (this option was added in 1.17.0).
terraform version
Fix: upgrade the CLI (Module 6) and, in required_version declare >= 1.17.0, to prevent older runners from running it.
Error: Failed to install provider ... the cached package for registry.terraform.io/kreuzwerker/docker 4.7.0 (in .terraform/providers) does not match any of the checksums recorded in the dependency lock file
Cause: the package in the cache does not match the hash in the lock file: the lock file recorded only other platforms' hashes, the cache was corrupted by concurrent writes, or the lock file was tampered with (fault 7).
grep -A8 'kreuzwerker/docker' .terraform.lock.hcl ls -l ~/.terraform.d/plugin-cache/registry.terraform.io/kreuzwerker/docker/
Fix: restore the correct lock file (git checkout .terraform.lock.hcl); if a platform is missing, run terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 ...; delete suspicious cache directories and re-download.
plan finishes quickly, but apply reports “No such container” or the resource has already been deleted
Cause: used -refresh=false or -minimal-refresh; plan did not detect drift, and only during apply did the provider find that the real object no longer exists.
Fix: re-run a full terraform plan; keep a full refresh for the apply pipeline.
occasional “text file busy” or provider binary corruption when multiple CI jobs run init at the same time
Cause: concurrent writes to a shared plugin cache (the official behavior is undefined).
Fix: use an independent cache directory per job, restored via the CI cache; or add a file lock on the shared cache to serialize init.
1. Enable the plugin cache for the current shell and verify that it takes effect.
mkdir -p ~/.terraform.d/plugin-cache && export TF_PLUGIN_CACHE_DIR=~/.terraform.d/plugin-cache rm -rf .terraform/providers && terraform init >/dev/null && ls -la .terraform/providers/registry.terraform.io/kreuzwerker/docker/*/
2. List the 5 resources that take the longest during apply.
terraform apply -auto-approve -json | jq -r 'select(.type=="apply_complete") | "\(.hook.elapsed_seconds)\t\(.hook.resource.addr)"' | sort -rn | head -5
The team wants to use -refresh=false in all pipelines to speed things up. Do you agree? Give an alternative.
I do not agree with using it everywhere: it makes plans based on stale state, misses manual deletions and changes, and may cause apply failures or incorrect changes. Alternative: PR plans use -minimal-refresh (refreshes only resources with changes, and still plans them correctly); apply uses a full refresh; nightly plan -refresh-only -detailed-exitcode detects drift; split stacks by change frequency over the long term; if the root cause of slow refresh is too many data sources, pass values in as variables or use remote state outputs.
Verified teaching videos
No dedicated video verifiable via oEmbed was found covering Terraform performance optimization (parallelism / minimal-refresh / plugin cache). Please use the storyboard below.
Official docs
- terraform plan (-refresh, -parallelism, and other options)
- Provider Plugin Cache
- Machine-readable UI (-json events)
- Terraform v1.17.0 release notes (-minimal-refresh)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: a timeline split into init, refresh, plan, and apply segments; the refresh segment is the longest.
Narration: measure before optimizing. In large stacks, time is usually spent on refresh: every resource must read its real state once.
Visual: five hundred blocks; with a full refresh all of them flash; with minimal refresh only twenty flash; with refresh=false none flash.
Narration: minimal refresh, added in version 1.17, refreshes only resources with proposed changes. It is faster, but drift in other resources is not visible.
Visual: a Gantt chart; parallelism rises from 2 to 10, bars overlap more, but the critical path length does not change.
Narration: parallelism only compresses the parts that can run at the same time; the critical path sets the lower bound; on cloud APIs, too much concurrency triggers throttling.
Visual: init drops from seven seconds to one second, with plugin cache dir shown beside it.
Narration: the plugin cache stops init from downloading again. Remember, the cache directory must be created in advance, and it is not guaranteed to be concurrency-safe.
Module 6 · Upgrading Terraform and providers
- Establish the upgrade process for the Terraform CLI and providers; understand
required_version,required_providersversion constraints and.terraform.lock.hcl's division of responsibilities. - Be able to use
terraform version,terraform init -upgrade,terraform providers lock -platform=..., andterraform providers; be able to migrate step by step following provider major-version upgrade guides (AWS 6.0, etc.). - Understand the OpenTofu migration steps, rollback capability, and major differences (state encryption, registry, release cadence); be able to trial-migrate on a lab stack and roll back.
What: what each of the three things manages
| File / setting | What it manages | Maintained by |
|---|---|---|
required_version = "~> 1.17" | Range of Terraform CLI versions allowed to run the configuration | Code author |
required_providers { docker = { version = "~> 4.7" } } | Allowed provider version range (since 1.17, variable/local can be referenced) | Code author (tighten in root modules, loosen in shared modules) |
.terraform.lock.hcl | Exact selected provider version + hashes for each platform package (h1:/zh:) | terraform init Generated, committed to Git |
The terraform_version and resources schema_version | in state: version of the last writer; resource schema version | written automatically, one-way upgrade |
Why: why upgrade regularly
- Security fixes (e.g., mitigation for HTTP/2 resource exhaustion in 1.16.6, Go runtime certificate fixes).
- New capabilities: in 1.17,
-minimal-refresh, Terraform Policy GA; new provider resources and bug fixes. - The longer you wait, the more major versions you cross, and the riskier a one-time migration becomes. The AWS provider releases weekly; azurerm has now reached 5.x.
How: standard upgrade process
- Read: the CLI CHANGELOG, the provider CHANGELOGs, and the major-version upgrade guides (AWS “Version 6 Upgrade Guide”, the azurerm 5.0 upgrade guide, etc.).
- First move to the latest minor version of the previous major version: for example, for AWS upgrade to the latest 5.x first, run plan and clear all deprecation warnings, and then move to 6.x (as recommended by the official upgrade guide).
- Change the constraint:
version = "~> 6.0"; for the CLI, changerequired_version. - Update the lock file:
terraform init -upgrade, thenterraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64to add platform hashes for the team and CI. - Plan environment by environment: dev → staging → prod, expecting “No changes” or only the changes described in the upgrade guide; stop at any unexpected replace.
- Rollback plan: before upgrading,
state pullback up state; state schema upgrades are irreversible, and rolling back the provider version requires restoring the state backup.
Verified key points of major-version migrations (summary; the official upgrade guides are authoritative)
| Provider | Current version (2026-11) | Major-version migration key points |
|---|---|---|
| hashicorp/aws | 6.73.0 (2026-11-11) | 6.0: removes OpsWorks/SimpleDB/Worklink resources and their corresponding endpoint parameters; some boolean attributes no longer accept 0/1; aws_ami data sources most_recent = true must set owners or the corresponding filter; many single-level nested blocks become lists (references need [0]); aws_api_gateway_deployment removes stage-related parameters; aws_redshift_cluster default encrypted = true,publicly_accessible = false |
| hashicorp/azurerm | 5.14.0 (2026-11-13) | 4.0: subscription_id becomes required, and provider automatic registration changes to resource_provider_registrations; for breaking changes in 5.0, read the official 5.0 upgrade guide (not verified item by item in this hour) |
| kreuzwerker/docker | 4.7.0 (2026-11-11) | for changes from 3.x → 4.x, read that repository's CHANGELOG; this lab pins ~> 4.7 |
Terraform CLI 1.x compatibility promises
HashiCorp commits to compatibility within the 1.x series: the configuration language, state format, and so on remain compatible between 1.x versions (see the official “Terraform v1.x Compatibility Promises” for details). However,state written by a newer CLI may not be readable by an older CLI, so teams must upgrade together and keep CI and developer machine versions identical (enforced with required_version ).
When: OpenTofu migration
OpenTofu is an open-source fork of Terraform under the Linux Foundation (MPL-2.0); its current version is 1.13.x (1.13.9, 2026-11-05), and 1.12.x still gets patches. Official migration guide steps: ① back up state and code → ② install OpenTofu → ③tofu init → ④tofu plan (expect No changes; do not apply if there are unexpected changes) → ⑤tofu apply (may update the state format even without infrastructure changes) → ⑥ verify with a small change. Rollback: stop using tofu → restore from backup if state changed → terraform init + terraform plan confirm.
| Dimension | Terraform 1.17 | OpenTofu 1.13 |
|---|---|---|
| License | BSL 1.1 | MPL-2.0 |
| Provider source | registry.terraform.io | OpenTofu Registry (most providers are available under the same name) |
| State encryption | No client-side encryption (relies on backend encryption) | Native state/plan encryption (since 1.7); key providers: PBKDF2, AWS KMS, GCP KMS, Azure Key Vault, OpenBao, external programs, etc. |
| Exclude resources | -target | -target and -exclude |
| HCP Terraform / Policy | Native integration; Terraform Policy GA (1.17) | HCP Terraform-specific features are not supported; platforms such as Spacelift and env0 can be used |
| 1.13 new features | — | Windows ARM64, new functions that reduce unknown values at plan time, lint experiment, symbol libraries experiment (per the OpenTofu docs) |
terraform_remote_state with multiple stacks that read from each other, sequence the migration per OpenTofu's “Migrating interdependent configurations” guide.terraform init -upgrade “init -upgrade will upgrade Terraform itself” — it does not; it only upgrades providers and modules within the constraints. ② “A lock file with only the Linux hashes is enough” — Mac and Windows developer machines will report checksum mismatches during init, or the lock file will show a large diff. ③ “If plan shows changes after a provider upgrade, just apply as usual” — check each change against the upgrade guide: is it an expected change (such as a changed default), or an unexpected replace?Flowchart: upgrade pipeline
Lock file structure
Interactive simulation: the gates of the upgrade pipeline
Choose an upgrade scenario and click “Next gate” to advance step by step. Each gate shows the real commands you would run and possible output, as well as where this scenario should be stopped.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
terraform version / -json | CLI and selected provider versions | shows whether a newer version exists (out-of-date notice) |
terraform providers | which providers the configuration and state need | finds legacy source addresses |
terraform init -upgrade | upgrade providers and modules within constraints | modifies the lock file |
terraform providers lock -platform=… | writes hashes for multiple platforms | can be repeated for multiple -platform |
terraform providers mirror DIR | download providers to a local mirror directory | offline / intranet environments |
tofu init / tofu plan | OpenTofu equivalent command | commands and parameters are largely compatible |
1. Check the current version
cd ~/tf-lab/part7/app
terraform version
terraform version -json | jq '{terraform_version, provider_selections, terraform_outdated}'
Terraform v1.17.2
on linux_amd64
+ provider registry.terraform.io/hashicorp/local v2.5.3
+ provider registry.terraform.io/hashicorp/random v3.7.2
+ provider registry.terraform.io/kreuzwerker/docker v4.7.0
{
"terraform_version": "1.17.2",
"provider_selections": { "registry.terraform.io/kreuzwerker/docker": "4.7.0", ... },
"terraform_outdated": false
}
The minor version numbers for random/local are examples; follow your own init results.
2. Simulate a provider upgrade: downgrade first, then upgrade
sed -i 's/version = "~> 4.7"/version = "4.6.0"/' versions.tf terraform init -upgrade >/dev/null && terraform version | grep docker terraform plan -lock=false | tail -1 sed -i 's/version = "4.6.0"/version = "~> 4.7"/' versions.tf terraform init -upgrade | grep -i docker git diff --stat .terraform.lock.hcl
+ provider registry.terraform.io/kreuzwerker/docker v4.6.0 No changes. Your infrastructure matches the configuration. - Finding kreuzwerker/docker versions matching "~> 4.7"... - Installing kreuzwerker/docker v4.7.0... .terraform.lock.hcl | 30 +++++++++++++++---------------
~> 4.7 is enough.3. Fill in hashes for all platforms in the team
terraform providers lock -platform=linux_amd64 -platform=linux_arm64 -platform=darwin_arm64 -platform=windows_amd64 grep -c 'h1:' .terraform.lock.hcl
4. Upgrade the Terraform CLI (apt source)
sudo apt-get update && apt-cache policy terraform | head -5 sudo apt-get install -y terraform=1.17.2-1 terraform version
Package versions in the HashiCorp apt source carry -1 suffixes; use apt-cache madison terraform to view available versions. In CI, it is recommended to pin a version (for example hashicorp/setup-terraform version in terraform_version: 1.17.2).
5. OpenTofu trial migration (on a copy)
cp -r ~/tf-lab/part7/app ~/tf-lab/part7/app-tofu && cd ~/tf-lab/part7/app-tofu rm -rf .terraform terraform -chdir=../app state pull > ../backups/before-tofu.tfstate tofu version tofu init tofu plan -lock=false
OpenTofu v1.13.9 on linux_amd64 ... Initializing provider plugins... - Installing kreuzwerker/docker v4.7.0... ... No changes. Your infrastructure matches the configuration.
The copy uses the same backend key: only run plan, do not apply, so tofu does not write state that would affect Terraform's later labs. For a real migration, confirm there are no changes before tofu apply, and switch the whole team over. Whether OpenTofu fetches the same package version from its registry as Terraform, and whether the lock file's h1 needs updating, should be determined by the output of tofu init .
Lab 6: a complete upgrade rehearsal (about 7 minutes)
cd ~/tf-lab/part7/app && git checkout -b upgrade-docker-provider terraform state pull > ../backups/before-upgrade.tfstate
git add versions.tf .terraform.lock.hcl && git commit -qm "chore: kreuzwerker/docker ~> 4.7 (4.7.0), lock 4 platforms" git show --stat HEAD
../faultbox.sh inject 7 terraform init 2>&1 | grep -A3 Error
│ Error: Failed to install provider │ │ Error while installing kreuzwerker/docker v4.7.0: the local package for registry.terraform.io/kreuzwerker/docker 4.7.0 │ doesn't match any of the checksums previously recorded in the dependency lock file ...
git checkout -- .terraform.lock.hcl && terraform init >/dev/null && echo fixed
Think: if this change appeared in a PR, how would the reviewer spot it? (In the lock file diff, h1:/zh: a hash change while the version stays the same is a strong signal of a supply-chain anomaly.)
tofu plan, confirm No changes; then rm -rf ~/tf-lab/part7/app-tofu.git checkout master 2>/dev/null || git checkout main; git merge upgrade-docker-provider (or discard the branch),terraform plan expect No changes.Case 1: staged migration of AWS provider 5 → 6
Problem: 40 stacks use AWS provider 5.x, some of which use aws_api_gateway_deployment stage_name. Approach: first upgrade everything to the latest 5.x and clear deprecation warnings; for stacks using stage_name, add aws_api_gateway_stage and import the existing stage; then change the constraint to ~> 6.0, and plan environment by environment. Configuration: Renovate automatically opens PRs for minor version updates; major versions are handled manually by the platform team. Limitation: shared modules must first publish transitional versions compatible with both 5 and 6 (version = ">= 5.90, < 7.0"), so that callers can migrate gradually.
Case 2: CI and developer machine CLI versions differ
Problem: a developer applied state with a newer version locally, and the older CLI in CI then reported that it could not read the state. Approach: set required_version = "~> 1.17.0" in all root modules; pin the version in CI; on developer machines, use tfenv or mise to read .terraform-version from the repository. Limitation: an overly tight constraint forces code changes even for patch upgrades; you can use ~> 1.17 and pin the patch version in CI.
Case 3: evaluating a migration to OpenTofu to use state encryption
Problem: compliance requires state to be encrypted on the client side. Approach: trial-migrate on a non-production stack (tofu init/plan with no changes), configure PBKDF2 → later change to the KMS key provider's encryption block, first use the unencrypted method for the transitional migration; assess whether HCP Terraform features and Terraform 1.16+ new syntax are in use. Limitation: once the key is lost after encryption, state cannot be read, so back up the key and state first; migrating back to Terraform requires decrypting first.
Common errors and fixes
Error: Unsupported Terraform Core version ... This configuration does not support Terraform version 1.16.7. To proceed, either choose another supported Terraform version or update this version constraint.
Cause:required_version the current CLI is not allowed.
Fix: upgrade the CLI to a version that satisfies the constraint; do not loosen the constraint just to let an old runner pass.
Error: Inconsistent dependency lock file ... provider registry.terraform.io/kreuzwerker/docker: locked version selection 4.6.0 doesn't match the updated version constraints "~> 4.7"
Cause: the constraint was changed without updating the lock file.
terraform init -upgrade
Fix: commit the lock file after running the update.
Error: Failed to query available provider packages ... Could not retrieve the list of available versions for provider hashicorp/docker: provider registry registry.terraform.io does not have a provider named registry.terraform.io/hashicorp/docker
Cause: a module does not declare required_providers, so Terraform infers hashicorp/docker by default (which does not exist).
terraform providers
Fix: declare docker = { source = "kreuzwerker/docker" } in every module that uses docker resources (the Lab 2 module is written this way).
After upgrading a provider, plan shows many “must be replaced”
Cause: changed defaults, changed attribute semantics (e.g., AWS 6.0 nested blocks became lists, Redshift default changes), or a provider bug.
Fix: do not apply. Work through the upgrade guide item by item (explicitly write the old defaults to keep the current behavior); roll back the version for replacements you cannot explain, and check the issues.
tofu init: Error: Failed to query available provider packages (a provider is not available in the OpenTofu Registry)
Cause: a few providers are not published to the OpenTofu Registry, or a module from a HashiCorp private registry is used.
Fix: search the OpenTofu Registry for an alternative; configure provider_installation to use a mirror; decide whether to migrate only after confirming.
1. Without upgrading the provider version, fill in lock file hashes for linux_amd64 and darwin_arm64.
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64
2. Output all currently selected provider versions with a single command (JSON).
terraform version -json | jq .provider_selections
You are responsible for upgrading a production stack that uses AWS provider 5.40 to 6.x. Write your steps and rollback plan.
Steps: ① read the 6.0 upgrade guide and the CHANGELOG after 5.40; ② first upgrade to the latest 5.x and run plan to clear all deprecation warnings (e.g., api_gateway_deployment's stage_name, aws_ami's owners); ③ state pull for a backup, and confirm S3 versioning; ④ change the constraint to ~> 6.0,init -upgrade,providers lock multi-platform; ⑤ compare dev/staging plans item by item, explicitly writing old defaults to avoid unexpected changes; ⑥ apply to prod within the maintenance window. Rollback: revert the constraint and lock file; if 6.x has already written state so that 5.x cannot read it (newer provider version), restore state from the backup or object version, then confirm with a 5.x plan.
Verified teaching videos
Official docs
- Dependency Lock File
- terraform providers lock
- Terraform v1.x Compatibility Promises
- AWS Provider Version 6 Upgrade Guide
- OpenTofu Migration Guide
- OpenTofu State Encryption
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: three cards: required_version, required_providers, lock file, labeled respectively “CLI scope”, “provider scope”, and “exact version plus hashes”.
Narration: constraints decide the allowed range; the lock file records the actual choices and hashes. The lock file must be committed to Git.
Visual: six pipeline gates light up in turn: read CHANGELOG, go to the latest of the previous major version, change the constraint, init upgrade, dev plan, roll out environment by environment.
Narration: an upgrade is a planned change. Read the upgrade guide first, move to the latest version of the previous major version, and clear deprecation warnings.
Visual: a red “must be replaced” appears in the plan output; the pipeline stops, and a rollback arrow points to the backup.
Narration: stop at any unexpected replacement. The state schema upgrade is one-way; rollback depends on backups.
Visual: terraform and tofu terminals side by side; tofu plan shows No changes; state encryption is listed beside them.
Narration: OpenTofu migration is also backup, init, plan, and apply only after there are no changes, and it can be rolled back. One of its distinguishing features is native state encryption.
Module 7 · Customization: external data, terraform_data, and provider development basics
- Be able to use
hashicorp/externaldata sources to call scripts, understanding the stdin/stdout JSON protocol and its limits (read-only, values must be strings). - Be able to use the built-in
terraform_dataresource (replacingnull_resource):input/output,triggers_replace, andreplace_triggered_byto work together. - Use Terraform Plugin Framework to write a minimal data-source provider, using
dev_overridesfor local debugging, and see your own provider's gRPC calls in the TRACE logs.
What: the four-rung extension ladder
| Level | Tool | Suitable for | Not suitable for |
|---|---|---|---|
| 1 | built-in functions / provider-defined functions (1.8+) | pure computation (strings, CIDR, encoding) | needs to access external systems |
| 2 | data "external" | read-only queries: calling a script to get Git info or internal CMDB values | creating/modifying resources; returning nested structures |
| 3 | terraform_data + provisioner / replace_triggered_by | triggering a one-time action when a value changes (initializing data, notifications) | needs real lifecycle management (read, drift detection, delete) |
| 4 | custom provider (Plugin Framework) | internal platform APIs needing full CRUD, import, and drift detection | one-off scripts |
Why: why you should not use local-exec for everything
provisioner (local-exec/remote-exec) is officially a “last resort”: Terraform cannot know what it did, cannot detect drift, resources are marked tainted after failure, and destruction is hard to get right. terraform_data Making the “trigger condition” an explicit value change visible in plan is clearer than null_resource + triggers , and it is a built-in resource that needs no additional provider.
How: the external data source protocol
- Terraform executes
program(array form, not through a shell), and writesquery(a string map) as a JSON object to the program's stdin. - The program must print to stdout stdout a JSON object,all values must be strings; the result appears in the
resultattribute. - a non-zero exit code is treated as failure, and the stderr content appears in the error.
- It runs on every plan (the data source is read during refresh/plan), so the program must be fast and free of side effects.
How: structure of the Plugin Framework
A provider is a Go program that main() calls providerserver.Serve to start a gRPC service (Plugin Protocol v6). You implement several interfaces:
| Interface | Required methods | Corresponding gRPC |
|---|---|---|
provider.Provider | Metadata, Schema, Configure, Resources, DataSources | GetProviderSchema, ConfigureProvider |
datasource.DataSource | Metadata, Schema, Read | ReadDataSource |
resource.Resource | Metadata, Schema, Create, Read, Update, Delete | PlanResourceChange, ApplyResourceChange, ReadResource |
Optional: ResourceWithImportState,ResourceWithModifyPlan,ResourceWithValidateConfig | ImportState, ModifyPlan… | ImportResourceState… |
latest framework version v1.19.0 (2026-03). HashiCorp recommends the Plugin Framework over the legacy SDKv2 for new providers. Minimum Go and Terraform versions follow the current official tutorial.
When: which level to choose
- “I just want to read a value” → external (or
httpdata source). - “Run initialization once whenever a value changes” → terraform_data.
- “I need to manage a class of objects over the long term, and let the team use it like AWS resources” → write a provider and pair it with
terraform-plugin-testingacceptance tests.
Comparison with similar technologies
| external | terraform_data | null_resource | custom provider | |
|---|---|---|---|---|
| requires an additional provider | hashicorp/external | no (built in, 1.4+) | hashicorp/null | yes |
| lifecycle | read-only | creation/replacement (triggered) | same as left | full CRUD + import |
| drift detection | re-read every time | none | none | yes (Read) |
jsondecode(). ② “Use external to call an API to create resources” — data sources run on every plan, so this would create duplicates repeatedly, and there is no delete logic. ③ “A written provider must be published to the Registry before it can be used” — for local development use dev_overrides; internal use can live in a private registry or a filesystem mirror.Data flow of the external data source
Structure and calls of a minimal provider
Timing animation: external protocol vs. custom provider RPC
Choose one extension method and step through the real interactions among core, the provider, and the external program. The log below shows the corresponding lines you can find in TF_LOG=TRACE (format example).
Core commands and configuration
| Command / configuration | Purpose | Notes |
|---|---|---|
data "external" | run the program to get a string map | program,query,working_dir |
resource "terraform_data" | save values / trigger replacement | input,output (= input),triggers_replace |
lifecycle { replace_triggered_by = [...] } | replaces this resource when a referenced resource or attribute changes | can only reference managed resources (terraform_data can conveniently wrap variables) |
go mod init / go get / go install | build the provider | the binary name must be terraform-provider-<NAME> |
dev_overrides | override the provider installation for local development | written in the CLI configuration file; when in effect, skips init |
TF_LOG_PROVIDER=DEBUG | see tflog.Debug output in the provider | use terraform-plugin-log |
1. external: read Git info as an image tag
#!/usr/bin/env bash
set -euo pipefail
# stdin: {"dir": "..."} stdout: string map
dir=$(jq -r '.dir')
cd "$dir"
sha=$(git rev-parse --short HEAD 2>/dev/null || echo "nogit")
branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "none")
dirty=$([ -n "$(git status --porcelain 2>/dev/null)" ] && echo "true" || echo "false")
jq -n --arg sha "$sha" --arg branch "$branch" --arg dirty "$dirty" '{sha:$sha, branch:$branch, dirty:$dirty}'
terraform {
required_providers {
external = { source = "hashicorp/external", version = "~> 2.3" }
}
}
data "external" "git" {
program = ["bash", "${path.module}/scripts/gitinfo.sh"]
query = { dir = path.module }
}
output "git" { value = data.external.git.result }
chmod +x scripts/gitinfo.sh
echo '{"dir":"."}' | ./scripts/gitinfo.sh # test the script on its own first
terraform init -upgrade >/dev/null && terraform apply -auto-approve | tail -6
{"sha":"9f2c1ab","branch":"main","dirty":"true"}
Outputs:
git = tomap({
"branch" = "main"
"dirty" = "true"
"sha" = "9f2c1ab"
})
Common errors: outputs a number or boolean ("dirty": true) → “Program output must be a JSON encoded map of string keys and string values”. The external version number ~> 2.3 is an example constraint; use the latest version in the Registry.
2. terraform_data: automatically initialize data when redis is rebuilt
resource "terraform_data" "redis_seed" {
triggers_replace = [docker_container.redis.id] # redis replaced → this resource replaced → re-executed
input = docker_container.redis.name
provisioner "local-exec" {
command = "sleep 2 && docker exec ${self.input} redis-cli SET seeded \"$(date +%s)\""
}
}
# wrap the variable with terraform_data so that a change to the variable can trigger replacement
variable "app_version" { default = "1.0" }
resource "terraform_data" "app_version" { input = var.app_version }
# add to docker_container.web:
# lifecycle { replace_triggered_by = [terraform_data.app_version] }
terraform apply -auto-approve >/dev/null docker exec p7-redis redis-cli GET seeded terraform apply -auto-approve -replace=docker_container.redis | grep -E 'redis_seed|Apply complete'
"1763201234" terraform_data.redis_seed: Destroying... [id=7c2b…] terraform_data.redis_seed (local-exec): Executing: ["/bin/sh" "-c" "sleep 2 && docker exec p7-redis redis-cli SET seeded …"] terraform_data.redis_seed (local-exec): OK Apply complete! Resources: 2 added, 0 changed, 2 destroyed.
3. Minimal provider: initialization and build
mkdir -p ~/tf-lab/part7/terraform-provider-p7 && cd ~/tf-lab/part7/terraform-provider-p7 go mod init example.com/lab/terraform-provider-p7 go get github.com/hashicorp/terraform-plugin-framework@v1.19.0 go get github.com/hashicorp/terraform-plugin-log
package main
import (
"context"
"log"
"os"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/provider"
pschema "github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
)
// ---------- provider ----------
type p7Provider struct{ version string }
func (p *p7Provider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "p7"
resp.Version = p.version
}
func (p *p7Provider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = pschema.Schema{Description: "Part 7 lab provider"}
}
func (p *p7Provider) Configure(_ context.Context, _ provider.ConfigureRequest, _ *provider.ConfigureResponse) {}
func (p *p7Provider) Resources(_ context.Context) []func() resource.Resource { return nil }
func (p *p7Provider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{func() datasource.DataSource { return &hostDS{} }}
}
// ---------- data source: p7_hostinfo ----------
type hostDS struct{}
type hostModel struct {
Prefix types.String `tfsdk:"prefix"`
Hostname types.String `tfsdk:"hostname"`
Label types.String `tfsdk:"label"`
}
func (d *hostDS) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_hostinfo"
}
func (d *hostDS) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"prefix": schema.StringAttribute{Optional: true, Description: "label prefix"},
"hostname": schema.StringAttribute{Computed: true},
"label": schema.StringAttribute{Computed: true},
},
}
}
func (d *hostDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var m hostModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
h, err := os.Hostname()
if err != nil {
resp.Diagnostics.AddError("cannot read hostname", err.Error())
return
}
tflog.Debug(ctx, "p7_hostinfo read", map[string]any{"hostname": h})
m.Hostname = types.StringValue(h)
m.Label = types.StringValue(m.Prefix.ValueString() + h)
resp.Diagnostics.Append(resp.State.Set(ctx, &m)...)
}
func main() {
err := providerserver.Serve(context.Background(),
func() provider.Provider { return &p7Provider{version: "0.1.0"} },
providerserver.ServeOpts{Address: "example.com/lab/p7"})
if err != nil {
log.Fatal(err)
}
}
go mod tidy && go install . && ls -l $(go env GOPATH)/bin/terraform-provider-p7
The code is based on the public interfaces of Plugin Framework v1.x (provider.Provider,datasource.DataSource,providerserver.Serve). If compilation reports an interface mismatch, compare with the official scaffolding template current style and adjust.
Lab 7: get your own provider running (about 7 minutes)
main.go and go install ..GOBIN=$(go env GOPATH)/bin
cat >> ~/.terraformrc <<EOF
provider_installation {
dev_overrides {
"example.com/lab/p7" = "$GOBIN"
}
direct {}
}
EOF
tail -7 ~/.terraformrcmkdir -p ~/tf-lab/part7/p7-demo && cd ~/tf-lab/part7/p7-demo
cat > main.tf <<'EOF'
terraform {
required_providers {
p7 = { source = "example.com/lab/p7" }
}
}
data "p7_hostinfo" "me" { prefix = "lab-" }
output "label" { value = data.p7_hostinfo.me.label }
EOF
terraform plan
╷ │ Warning: Provider development overrides are in effect │ │ The following provider development overrides are set in the CLI configuration: │ - example.com/lab/p7 in /home/azureuser/go/bin │ │ The behavior may therefore not match any released version of the provider and applying changes may cause the │ state to become incompatible with published releases. ╵ Changes to Outputs: + label = "lab-lab-vm"
With dev_overrides in effect, you do not need (and should not) run terraform init for this provider.
TF_LOG=TRACE terraform plan 2>&1 | grep -E 'terraform-provider-p7|GRPCProvider|p7_hostinfo read' | head -12
[DEBUG] provider: starting plugin: path=/home/azureuser/go/bin/terraform-provider-p7 ... [TRACE] GRPCProvider.v6: GetProviderSchema [TRACE] GRPCProvider.v6: ValidateDataResourceConfig [TRACE] GRPCProvider.v6: ConfigureProvider [TRACE] GRPCProvider.v6: ReadDataSource [DEBUG] provider.terraform-provider-p7: p7_hostinfo read: hostname=lab-vm ...
The Framework uses protocol v6, so core logs show GRPCProvider.v6. This is the same mechanism as the Docker provider call chain in Module 1.
Read , remove the assignment of m.Label (leave it unassigned),go install . then run plan — what happens when a Computed attribute stays unknown/null? Observe the Terraform error and classify it as a “provider bug” from Module 4. Restore the code afterwards.~/.terraformrc delete the provider_installation block (otherwise every directory will show the dev override warning,direct {} and it also changes installation behavior beyond the plugin cache); rm -rf ~/tf-lab/part7/p7-demo.Case 1: using external to read the cost center from an internal CMDB
Problem: all resources need a cost-center tag, and the data lives in the internal CMDB. Approach: external calls a read-only Python script (with timeout and caching) that returns {"cost_center":"cc-1042"}, referenced in default_tags . Limitation: every plan calls the CMDB; when the CMDB is unavailable, all plans fail — it was later changed so that CI generates tags.auto.tfvars, reducing coupling.
Case 2: terraform_data replaces null_resource to trigger a database migration
Problem: a database migration must run once whenever the application version changes. Approach:terraform_data The triggers_replace = [var.app_version] resource, local-exec invokes the migration Job; before 1.4, the null_resource using moved { from = null_resource.migrate to = terraform_data.migrate } for the migration (Terraform supports this cross-type moved; follow the official docs). Limitation: if migration fails, the resource is marked tainted and re-runs on the next apply, so the migration script must be idempotent.
Case 3: writing a provider for an internal gateway platform
Problem: the team manages routes of an internal API gateway with 30 curl scripts, which cannot be audited or rolled back. Approach: write a provider based on scaffolding-framework, with resource gw_route implementing CRUD + ImportState; write acceptance tests with terraform-plugin-testing; publish to a private registry. Limitation: the provider needs long-term maintenance (API changes, releases, signing); before investing, evaluate whether a community provider already exists or a general-purpose http/restapi-style provider can be used instead.
Common errors and fixes
Error: Unexpected External Program Results ... Program output must be a JSON encoded map of string keys and string values.
Cause: the script output a number, boolean, or nested object, or printed debugging information to stdout.
echo '{"dir":"."}' | ./scripts/gitinfo.sh | jq 'to_entries | map(select(.value|type!="string"))'
Fix: convert everything to strings (jq's --arg); write debugging information to stderr.
Error: External Program Execution Failed ... The data source received an unexpected error while attempting to execute the program.
Cause: the script exited with a non-zero code (the error includes stderr), or the interpreter was not found / there is no execute permission.
Fix: run the script on its own to reproduce; program use an array and explicitly specify the interpreter (["bash", "..."]); on Windows, watch for path and interpreter differences.
Error: Failed to query available provider packages ... example.com/lab/p7: could not connect to example.com
Cause: dev_overrides is not in effect, yet terraform init was executed, so Terraform tries to download from example.com.
Fix: confirm that the address in ~/.terraformrc matches required_providers 's source exactly; when dev_overrides is in effect, skip init and run plan directly.
Error: Provider produced invalid object / unknown values after apply (the custom provider did not set Computed attributes)
Cause: after Read/Create, Computed attributes are still unknown, so core's consistency check rejects the result.
Fix: before returning, assign known values (or null) to all Computed attributes; cover this with checks in terraform-plugin-testing.
after the provisioner of terraform_data fails, the next apply always re-runs it
Cause: the provisioner failed at creation → the resource is marked tainted → it is replaced next time.
Fix: make the command idempotent; apply after fixing the root cause; if you really want to ignore it, on_failure = continue (use with caution).
1. Without running Terraform, test whether the external script's input and output comply with the protocol.
echo '{"dir":"."}' | bash scripts/gitinfo.sh | jq -e 'type=="object" and (map_values(type=="string") | all)'2. Make the web container be replaced when the app_version variable changes (write out the HCL snippet).
resource "terraform_data" "app_version" { input = var.app_version }
resource "docker_container" "web" {
# ...
lifecycle { replace_triggered_by = [terraform_data.app_version] }
}A colleague uses data "external" to call the Azure CLI to create a storage account (if it does not exist). Point out the problems and give an alternative.
Problem: the data source runs on every plan (including read-only plans in PRs), causing side effects; there is no delete logic, so resources remain after destroy; it is not in state, so drift cannot be detected; concurrent runs may create duplicates. Alternative: use azurerm's azurerm_storage_account resource; if it already exists, bring it under management with an import block; use external or the azurerm data source only for read-only queries.
Verified teaching videos
HashiCorp's official talks on the Plugin Framework (such as “A Modern Terraform Plugin Framework”) could not be confirmed with a YouTube link in this verification, so they are not listed; please use the official written tutorial and the storyboard below.
Official docs
- Terraform Plugin Framework
- Tutorial: Implement a provider with the Plugin Framework
- dev_overrides
- external data source
- terraform_data
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: a four-rung ladder: functions, external, terraform_data, custom provider; the higher you climb, the heavier it gets.
Narration: there are four rungs for extending Terraform. If a lower rung solves the problem, do not climb higher.
Visual: JSON flows from Terraform into the script's stdin and back out via stdout; all values are quoted.
Narration: the external data source communicates with scripts using JSON, and all values must be strings. It runs on every plan, so it must be read-only and fast.
Visual: variable app_version changes from 1.0 to 1.1; terraform_data flashes, and the web container is replaced along with it.
Narration: terraform_data is a built-in resource that can turn value changes into explicit replacement triggers, replacing the old null_resource.
Screen: Go code editor, main function calls providerserver Serve; the terminal shows “Provider development overrides are in effect” and GRPCProvider v6 ReadDataSource.
Narration: a custom provider is a gRPC service. Implement a few interfaces with the Plugin Framework, debug locally with dev overrides, and see your own provider being called in the TRACE logs.
Module 8 · Mixed fault blind box
- Without knowing the fault number, use the five-step method to classify a symptom within 5 minutes as core / state / provider / API / supply chain.
- For each fault, give a minimum-risk fix (prefer declarative changes, back up first, and get plan to No changes after the fix).
- Write a short postmortem: root cause, detection method, preventive measures.
faultbox.sh, Modules 1–7. Importance:★★★★★What: 8 faults
| # | Fault | First symptom | Layer | Related modules |
|---|---|---|---|---|
| 1 | stale lock (apply killed with kill -9) | Error acquiring the state lock | Core / backend | M2 |
| 2 | drift: container deleted manually | plan shows web[1] will be created | the real world | M2, M5 |
| 3 | dependency cycle | Error: Cycle | Core (configuration) | M3 |
| 4 | for_each unknown keys | Invalid for_each argument | Core (configuration) | M3 |
| 5 | provider cannot connect to Docker | Error pinging Docker server / connection refused | Provider / API connection | M1, M4 |
| 6 | resource renamed without a moved block | plan: 1 to add, 1 to destroy (redis) | State ↔ configuration | M2 |
| 7 | lock file hash tampered with | init: checksums mismatch | supply chain | M5, M6 |
| 8 | old state about to be pushed | push: cannot import state with serial ... over newer state | State | M2 |
Why: why practice with a blind box
In real incidents, nobody tells you “this is fault 6”. The blind box forces you to observe first, then hypothesize, then verify, instead of applying a memorized answer. Several faults look alike (2 and 6 both have plan wanting to create things; 1 and 8 both relate to state writes), so extra evidence is needed to tell them apart.
How: blind box rules
../faultbox.sh inject(no number = random); do not look at.fault.- Only start observing from
terraform plan/terraform init, and record the verbatim first error. - Write down a hypothesis and the verification command before attempting any fix.
- Acceptance:
terraform planis No changes (or only the expected changes remain),curl localhost:8080returns 200. - Finally,
cat .faultcheck the answer and record the time taken.
When: key evidence for telling similar symptoms apart
| Similar symptom | Distinguishing evidence |
|---|---|
| plan wants to create resources (2 vs 6) | fault 2: docker ps the container truly does not exist and the code is unchanged; fault 6: git diff shows a rename, plan has both an old-address destroy and a new-address create, and the real container is still running. |
| state write blocked (1 vs 8) | fault 1: any command reports a lock error, with Who/Created in Lock Info; fault 8: plan works normally, and only push is rejected. |
| provider cannot work (5 vs 7) | fault 5: init succeeds, but the connection fails during the ConfigureProvider phase at plan; check DOCKER_HOST; fault 7: init fails straight away with a checksum mismatch. |
-force/force-unlock/state rm” — these are all high-risk operations; confirm the evidence first. ② “If plan wants to create something, apply directly” — in fault 6, apply would destroy and recreate redis, causing an outage; the correct approach is a moved block. ③ “Finishing the code fix means you are done” — you must also confirm that state matches the real world, and write a postmortem.Diagnostic map: from the first error to the fault category
Postmortem template
In-browser fault simulator: blind box challenge
Click “Draw blind box” to inject a random fault. Use the “diagnostic commands” buttons below to collect evidence (each command counts as one action), then choose your conclusion under “Diagnosis and fix”. Simulated output is based on typical output of the real commands in this hour's labs. Goal: find the correct fix with the fewest commands. Scores are saved in this browser.
Standard fix command for each fault
| # | Diagnosis | Fix | Verification |
|---|---|---|---|
| 1 | terraform plan → Lock Info; ps aux | grep terraform; mc ls local/tfstate/part7/ | terraform force-unlock -force LOCK_ID | plan normal; check whether the interrupted apply left orphans (docker ps -a and state list compared) |
| 2 | terraform plan; docker ps -a --filter name=p7-web | investigate who deleted it → terraform apply recreate | curl 8081 = 200 |
| 3 | terraform validate; graph -type=plan -draw-cycles | locals to break the cycle / undo the mistakenly added reference | validate passes |
| 4 | the error in the plan: known only after apply | static map keys / -target two-phase | plan lists ["a"],["b"] |
| 5 | env | grep DOCKER; docker context ls; TF_LOG_PROVIDER=DEBUG | unset DOCKER_HOST (or correct) | plan is normal |
| 6 | git diff; plan shows destroy redis + create cache | add moved { from = docker_container.redis to = docker_container.cache } | plan shows has moved to, 0 add / 0 destroy |
| 7 | terraform init; git diff .terraform.lock.hcl | git checkout -- .terraform.lock.hcl && terraform init | init succeeds, lock file has no diff |
| 8 | push reports serial; jq .serial,.lineage compare the two files | do not push; apply after changing the code for the needed change | remote serial did not roll back |
Fault 1 detailed steps
terraform plan 2>&1 | sed -n '/Lock Info/,/^$/p' ps aux | grep -v grep | grep 'terraform apply' || echo "no running terraform" docker exec minio mc ls local/tfstate/part7/ terraform force-unlock -force 3f2a8c1e-… # use the ID from Lock Info terraform plan
Lock Info: ID: 3f2a8c1e-9b7d-4c61-a2f0-5e9d8b1c7a44 Path: tfstate/part7/app.tfstate Operation: OperationTypeApply Who: azureuser@lab-vm Version: 1.17.2 Created: 2026-11-15 11:02:17.48 +0000 UTC no running terraform [2026-11-15 11:02:17 UTC] 228B STANDARD app.tfstate.tflock [2026-11-15 10:58:40 UTC] 14KiB STANDARD app.tfstate Terraform state has been successfully unlocked! ... # docker_container.web[2] will be created ← may have been partially created before the kill; handle according to the plan
Fault 6 detailed steps
git diff --stat
terraform plan | grep -E '^\s+# docker_container\.(redis|cache)'
cat >> main.tf <<'EOF'
moved {
from = docker_container.redis
to = docker_container.cache
}
EOF
terraform plan | tail -3
# docker_container.cache will be created # docker_container.redis will be destroyed ... # docker_container.redis has moved to docker_container.cache Plan: 0 to add, 0 to change, 0 to destroy.
Lab 8: three rounds of blind boxes (about 8 minutes; can continue after class)
cd ~/tf-lab/part7/app && ../faultbox.sh reset && unset DOCKER_HOST terraform apply -auto-approve -var web_count=2 >/dev/null && terraform plan -detailed-exitcode >/dev/null; echo "exit=$?"
exit=0
-detailed-exitcode: 0 = no changes, 1 = error, 2 = changes present. This is the acceptance condition for the blind box.
../faultbox.sh inject → time it → observe (terraform init,terraform plan) → write the hypothesis on paper → verify → fix → terraform plan -detailed-exitcode is 0 → cat .fault check the answer. If it is fault 5, remember to follow the hint source .envrc-fault to take effect (this simulates “someone changed DOCKER_HOST in your shell config”).../faultbox.sh reset, and confirm that terraform plan returns to exit=0 (state-level faults you must clean up yourself).| Round | Time | First error | My hypothesis | Actual fault | Fix command | Prevention | |---|---|---|---|---|---|---| | 1 | 4m10s | Error: Cycle: ... | mutual references | #3 | locals | terraform validate in CI | | 2 | | | | | | | | 3 | | | | | | |
../faultbox.sh reset; unset DOCKER_HOST; rm -f .envrc-fault /tmp/p7-*.tfstate; terraform plan make sure plan shows No changes.Case 1: all pipelines deadlocked on Monday morning
Problem: a weekend maintenance script was killed by the ops platform's timeout during apply, leaving a lock; on Monday, 20 PR pipelines queued and failed. Approach: following the fault 1 procedure, confirm no process is running and unlock; plan found a half-created load balancer; after importing it, things returned to normal. Prevention: the maintenance script timeout > the slowest Terraform resource; the pipeline -lock-timeout=10m is set to a concurrency group; alert when a lock has existed for more than 1 hour.
Case 2: “why does plan want to rebuild the database?”
Problem: a refactoring PR renamed aws_db_instance.main to aws_db_instance.primary, and plan showed destroying and recreating the database. Reviewers caught it in time. Approach: add a moved block; plan becomes has moved to. Prevention: use terraform show -json tfplan | jq detects delete actions on stateful resources (databases, storage) and requires extra approval if present; on critical resources, set lifecycle { prevent_destroy = true }.
Case 3: abnormal hash in a lock file PR
Problem: in a “formatting” PR, the hash of .terraform.lock.hcl changed while the version did not. Approach: following fault 7, reject the merge; use terraform providers lock to regenerate in a clean environment and compare, confirming that the cache on the committer's machine was tampered with (or the mirror configuration was wrong). Prevention: CODEOWNERS requires platform-team review of lock file changes; in CI, use terraform init -lockfile=readonly, forbidding rewriting the lock file in CI.
Interactive troubleshooting decision tree: locating Terraform faults
Start from the first symptom you see, choosing level by level until you reach the diagnosis and fix commands. It covers the 8 blind-box faults in this hour and common issues from Modules 1–7.
1. Write a CI check that fails and exits when any resource action in the plan includes delete.
terraform plan -out=tfplan >/dev/null
terraform show -json tfplan | jq -e '[.resource_changes[] | select(.change.actions | index("delete"))] | length == 0' \
|| { echo "plan includes delete actions; manual approval required"; exit 1; }2. In CI, forbid modifying the lock file, and return 0 when there are no changes and 2 when there are changes.
terraform init -lockfile=readonly -input=false terraform plan -detailed-exitcode -input=false
plan shows docker_container.web[1] will be created, with no error at all. How do you tell whether this is drift (fault 2) or a configuration change? How do you handle each?
Evidence: ① git diff/git log check whether the code changed web_count or the resource address; ② docker ps -a --filter name=p7-web-1 check whether the container exists; ③ terraform state list check whether state has web[1]. If the code is unchanged, state has a record, but the container does not exist → drift: first investigate who deleted it and why (audit logs), then apply to recreate, and consider drift-detection alerts. If the code changed the count → a normal change. If the container exists but the address changed → a rename, which needs a moved block.
Verified teaching videos
No video on the topic “Terraform fault drills” that can be verified via oEmbed was found; please use the storyboard below.
Official docs
Video storyboard (about 100 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided for a video tool.
Visual: a gift box opens, a red error line pops out, and the timer starts.
Narration: the fault blind box: you don't know which fault it is, and can only start from the first error.
Visual: diagnostic map: four paths — init fails, fails before plan, plan errors, plan has changes — light up in turn with their corresponding fault numbers.
Narration: first see which step the error appears in. An init failure is most often the lock file; a failure before plan is most often a lock; for a plan error, check whether it is a cycle, an unknown key, or a connection problem; if plan succeeds with changes, distinguish drift from rename.
Visual: two similar plan outputs side by side: one next to a git diff showing a rename, the other next to a missing container in docker ps.
Narration: similar symptoms need extra evidence. Use a moved block for renames; for drift, investigate the cause before recreating.
Visual: plan with detailed exitcode returns zero, with a green check; the four-box postmortem card fills in.
Narration: the end point of a fix is a plan with no changes. Finally, write the postmortem: symptom, root cause, fix, prevention.
Command cheat sheet
Logs and diagnostics
TF_LOG=DEBUG terraform plan # core + provider TF_LOG_CORE=WARN TF_LOG_PROVIDER=DEBUG terraform plan TF_LOG=TRACE TF_LOG_PATH=./tf.log terraform apply # PATH must be used together with a level TF_LOG=JSON TF_LOG_PATH=tf.json terraform plan jq -r '."@module" // "core"' tf.json | sort | uniq -c terraform version -json terraform graph -type=plan -draw-cycles | dot -Tsvg > g.svg terraform console
State surgery
terraform state pull > backup-$(date +%s).tfstate terraform state list [-id=ID] terraform state show 'ADDR[0]' terraform state mv -dry-run SRC DST && terraform state mv SRC DST terraform state rm -dry-run ADDR && terraform state rm ADDR terraform state push FILE # check lineage/serial; do not use -force terraform state replace-provider OLD_FQN NEW_FQN terraform show -json | jq '.values.root_module.resources[].address' terraform force-unlock LOCK_ID terraform apply -replace=ADDR
Declarative refactoring (preferred)
moved {
from = docker_container.redis
to = docker_container.cache
}
removed {
from = local_file.inventory
lifecycle { destroy = false }
}
import {
to = docker_container.redis
id = "CONTAINER_ID"
}Dependencies and unknown values
# ✗ unknown keys
for_each = toset([for s in aws_subnet.x : s.id])
# ✓ static keys + unknown values
for_each = { for k, s in aws_subnet.x : k => s.id }
# break the cycle: put constants in locals
locals { redis_name = "p7-redis" }
# two-phase (bootstrap/recovery only)
# terraform apply -target=random_id.tag && terraform applyProvider behavior
resource "docker_container" "x" {
wait = true
wait_timeout = 60
timeouts { create = "5m" }
}
provider "aws" {
max_retries = 10 # default 25
retry_mode = "adaptive"
}
resource "time_sleep" "wait" { create_duration = "20s" }Performance
terraform apply -parallelism=5 terraform plan -minimal-refresh # 1.17+ terraform plan -refresh=false terraform plan -refresh-only -detailed-exitcode export TF_PLUGIN_CACHE_DIR=~/.terraform.d/plugin-cache # mkdir first terraform apply -json | jq -r 'select(.type=="apply_complete") | "\(.hook.elapsed_seconds)\t\(.hook.resource.addr)"' | sort -rn
Upgrades
terraform version terraform providers terraform init -upgrade terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 terraform init -lockfile=readonly # CI tofu init && tofu plan # OpenTofu trial migration (back up first)
Extensions
data "external" "git" {
program = ["bash", "${path.module}/scripts/gitinfo.sh"]
query = { dir = path.module } # stdout must be a string map
}
resource "terraform_data" "seed" {
triggers_replace = [docker_container.redis.id]
input = docker_container.redis.name
}
# ~/.terraformrc
# provider_installation { dev_overrides { "example.com/lab/p7" = "/home/u/go/bin" } direct {} }Quick troubleshooting table
| Symptom (first error) | What to do first | Common causes | Module |
|---|---|---|---|
| Error acquiring the state lock | read Lock Info, confirm no process is running | process killed, concurrent runs | M2/M8 |
| cannot import state with serial … over newer state | compare serial/lineage | old backup / old local state | M2 |
| Failed to load state / unexpected end of JSON | restore object version | corrupted object, manual upload | M2 |
| Error: Cycle | graph -type=plan -draw-cycles | mutual references, mixed CBD, provider referencing resources | M3 |
| Invalid for_each/count argument | find the value that is known only after apply | key depends on a computed attribute | M3 |
| 429 / Throttling / exceeded max attempts | count DEBUG logs | concurrency too high, quota | M4 |
| timeout while waiting for state | check the actual cloud state | slow resources, timeouts too short | M4 |
| Provider produced inconsistent result | search provider issues | provider bug, API normalization | M4 |
| plugin crashed / panic | save the stack trace | provider bug | M4 |
| checksums … dependency lock file | git diff lock file | missing platform hashes, tampering, cache corruption | M5/M6 |
| Unsupported Terraform Core version | terraform version | CLI too old | M6 |
| Resource instance managed by newer provider version | check the lock file version | someone else wrote state with a newer provider | M2/M6 |
| Unexpected External Program Results | run the script on its own | script outputs non-string values | M7 |
For the complete interactive troubleshooting flow, see Module 8 → troubleshooting → decision tree.
Recommended configuration snippet: a root module that is easy to troubleshoot and upgrade
terraform {
required_version = "~> 1.17" # pin the patch version in CI
required_providers {
docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
}
backend "s3" {
# ... use_lockfile = true; bucket with versioning enabled
}
}
resource "docker_container" "db" {
# ...
lifecycle {
prevent_destroy = true # guards stateful resources against accidental deletion
}
}
# CI:
# terraform init -lockfile=readonly -input=false
# TF_LOG=INFO TF_LOG_PATH=$RUNNER_TEMP/tf.log terraform plan -minimal-refresh -lock-timeout=5m -out=tfplan -detailed-exitcode
# terraform show -json tfplan | jq -e '[.resource_changes[] | select(.change.actions|index("delete"))] | length == 0'
# nightly: terraform plan -refresh-only -detailed-exitcode (drift detection)
Integrated lab + final quiz
.fault); ② deliver a performance and operability report that makes the PR pipeline faster and safer; ③ turn the troubleshooting experience into CI checks. Everything is done on local Docker + MinIO, at zero cloud cost.cd ~/tf-lab/part7/app && ../faultbox.sh reset && unset DOCKER_HOST terraform init -input=false >/dev/null terraform apply -auto-approve >/dev/null terraform state pull > ../backups/final-baseline.tfstate terraform plan -detailed-exitcode >/dev/null; echo "baseline exit=$?" docker exec minio mc version info local/tfstate
baseline exit=0 local/tfstate versioning is enabled
~/tf-lab/part7/score.sh, which automatically injects, times, and verifies each round.
#!/usr/bin/env bash
# usage: ./score.sh (interactive, 5 rounds)
cd ~/tf-lab/part7/app
total=0
for round in 1 2 3 4 5; do
../faultbox.sh reset >/dev/null; unset DOCKER_HOST
../faultbox.sh inject >/dev/null
echo "=== Round $round: fault injected; start diagnosing (work in a new terminal); when fixed, come back here and press Enter ==="
start=$(date +%s); read -r _
used=$(( $(date +%s) - start ))
( unset DOCKER_HOST; terraform plan -detailed-exitcode -input=false >/dev/null 2>&1 ); rc=$?
fault=$(cat .fault)
if [ $rc -eq 0 ] && [ $used -le 360 ]; then pts=20; elif [ $rc -eq 0 ]; then pts=10; else pts=0; fi
total=$((total+pts))
echo "fault #$fault · time ${used}s · plan exit=$rc · score $pts"
done
echo "Total: $total / 100"
chmod +x ~/tf-lab/part7/score.sh && ~/tf-lab/part7/score.sh
The acceptance criterion is plan -detailed-exitcode returns 0: this means code, state, and the real world are consistent. Note that after fixing fault 4 (which appended a new resource), plan may return 2 (per_tag needs to be created); you must apply, or undo the appended code, so that it returns 0. For fault 8, as long as you did not push, plan itself returns 0 — that round tests whether you “recognize and refuse a dangerous operation”, so write your judgment in the record.
ci-check.sh:
#!/usr/bin/env bash
set -euo pipefail
terraform fmt -check -recursive
terraform init -lockfile=readonly -input=false >/dev/null # prevents fault 7: CI does not modify the lock file
terraform validate # prevents faults 3 / part of 4
TF_LOG=INFO TF_LOG_PATH="${RUNNER_TEMP:-/tmp}/tf.log" \
terraform plan -minimal-refresh -lock-timeout=5m -input=false -out=tfplan
terraform show -json tfplan > plan.json
# prevents fault 6: deleting a stateful resource requires manual approval
if jq -e '[.resource_changes[] | select((.change.actions|index("delete")) and (.type=="docker_container") and (.name=="redis" or .name=="cache"))] | length > 0' plan.json >/dev/null; then
echo "::error::plan will delete redis/cache; check whether a moved block is missing"; exit 1
fi
echo "CI checks passed"
cd ~/tf-lab/part7/app && bash ci-check.sh ../faultbox.sh inject 6 && bash ci-check.sh; echo "exit=$?"; ../faultbox.sh reset
CI checks passed ... ::error::plan will delete redis/cache; check whether a moved block is missing exit=1
cd ~/tf-lab/part7/app
m() { for i in 1 2 3; do /usr/bin/time -f "%e" "$@" >/dev/null 2>>/tmp/t.txt; done; sort -n /tmp/t.txt | sed -n 2p; : > /tmp/t.txt; }
echo "init(no cache): $(rm -rf .terraform/providers; TF_PLUGIN_CACHE_DIR= m terraform init -input=false)"
echo "init(cache): $(rm -rf .terraform/providers; m terraform init -input=false)"
echo "plan full: $(m terraform plan -lock=false)"
echo "plan minimal: $(m terraform plan -lock=false -minimal-refresh)"
echo "plan p=2: $(m terraform plan -lock=false -parallelism=2)"
“init(no cache)”: after the first run, the two subsequent repeated inits find .terraform/providers already present, so only the first run actually downloads; this is a limitation of the measurement method, so note it in the report (or delete the directory in every loop iteration).
../faultbox.sh reset; terraform destroy -auto-approve; if MinIO is no longer needed: docker rm -f minio && docker volume rm minio-data; delete the ~/.terraformrc blocks added in the lab. When the Azure VM is not in use, stop it or provider_installation deallocate it az group delete -n rg-tf-lab --yes --no-wait.Open-ended self-test (answer yourself first, then expand the reference answer)
1. Once terraform apply in the logs of creating a container, what can you see at each of the three layers: core, provider, and API?
core: provider startup,GRPCProvider: PlanResourceChange/ApplyResourceChange, vertex traversal, state writes; provider: SDK logs with the provider.terraform-provider-docker prefix; API: Docker Engine's POST /containers/create,/start,GET /json (requires socat packet capture; the AWS provider prints HTTP requests directly in DEBUG).
2. What are the two safety checks for state push? When can they be bypassed?
lineage must be the same; the target serial must not be higher than local. You should almost never use -force to bypass them; when state is corrupted, recover at the backend layer using object versions, not push -force.
3. Why can't for_each keys depend on values known only after apply? Give two fixes.
keys determine instance addresses, and plan must list the addresses and actions of all instances. Fixes: a map with static keys + unknown values; -target two-phase (bootstrap/recovery only).
4. apply reports timeout while waiting; what is your first step?
Check the actual state of the resource in the cloud or Docker. A timeout does not equal failure; decide between replace, import, or delete based on whether the resource is in state (and whether it is tainted), then consider adjusting timeouts.
5. -minimal-refresh and -refresh=false — what is the difference? How do you compensate for their blind spots?
The former (1.17+) refreshes only resources with proposed changes; the latter does not refresh at all. Neither can see drift in unchanged resources; use periodic plan -refresh-only -detailed-exitcode drift detection, and keep a full refresh in the apply pipeline.
6. In what situations would you write a custom provider instead of using external or terraform_data?
When you need to manage the full lifecycle of a class of objects over the long term (create, read/drift detection, update, delete, import) and want the team to reuse it declaratively. external is suitable only for read-only queries, and terraform_data only for triggering one-time actions.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verification result | Source (accessed 2026-11-15) |
|---|---|---|
| Terraform CLI version | Latest v1.17.2 (2026-11-11); v1.17.1 (2026-10-28); v1.17.0 (2026-10-21); v1.16.7 (2026-10-22) still gets patches. 1.17.0: provider requirements can use variable/local,-minimal-refresh (refresh only resources with proposed changes), Terraform Policy GA,mock_provider supports ephemeral resources,version JSON adds format_version; 1.17.2 fixes the provider reference destroy=false dependency cycle with managed resources | hashicorp/terraform releases |
| TF_LOG variable | TF_LOG: TRACE/DEBUG/INFO/WARN/ERROR/JSON; TF_LOG_CORE,TF_LOG_PROVIDER at the same level; TF_LOG_PATH appended to a file and must be set together with a level; JSON logs are not a stable interface | Debugging Terraform |
| terraform graph | option -plan,-draw-cycles (only with -type),-type=plan|plan-refresh-only|plan-destroy|apply; the default output shows a simplified resource dependency graph | terraform graph |
| state push | rejected when lineage differs or the target serial is higher; -force disabling the check is not recommended by the official docs | terraform state push |
| plugin cache | plugin_cache_dir / TF_PLUGIN_CACHE_DIR; the directory must already exist; by default it must match the lock file checksum; plugin_cache_may_break_dependency_lock_file setting it is not recommended; the cache is not guaranteed to be concurrency-safe; Terraform does not delete old versions from the cache | CLI Configuration File |
| S3 backend (MinIO) | use_lockfile (default false); DynamoDB locking is deprecated; endpoints.s3,use_path_style,skip_credentials_validation,skip_requesting_account_id,skip_metadata_api_check,skip_region_validation,skip_s3_checksum; non-AWS endpoints are best-effort supported | Backend Type: s3 |
| kreuzwerker/docker | Latest v4.7.0 (2026-11-11); v4.6.0 (2026-09-01). docker_container supports wait,wait_timeout (seconds, default 60, needs healthcheck),must_run,healthcheck,timeouts (create/update/delete) | releases · docker_container docs |
| AWS / azurerm provider | aws v6.73.0 (2026-11-11); azurerm v5.14.0 (2026-11-13). Key points of the AWS 6.0 upgrade: removes OpsWorks/SimpleDB/Worklink, stricter validation of boolean attributes,aws_ami most_recent requires owners/filter, single-level nested blocks become lists,aws_api_gateway_deployment removes stage parameters,aws_redshift_cluster default value changes; the official recommendation is to first upgrade to the latest 5.x and then change to ~> 6.0 | aws releases · Version 6 Upgrade Guide · azurerm releases |
| OpenTofu | latest v1.13.9 (2026-11-05), with 1.12.12 released the same day; 1.13.0 (2026-09-30): Windows ARM64, new functions that reduce unknown values, lint and symbol libraries experiments, no longer supports the WinRM provisioner. Migration steps: back up → install → tofu init → tofu plan → tofu apply → verify with a small change; rollback is possible. State encryption: PBKDF2, AWS KMS, GCP KMS, Azure Key Vault, OpenBao, external key providers; AES-GCM method | opentofu releases · Migration Guide · State Encryption |
| Plugin Framework | latest v1.19.0 (2026-03-10); v1.18.0 (2026-02-27) | terraform-plugin-framework releases · Docs |
Video verification note
The following videos were verified for title and channel through the YouTube oEmbed endpoint (2026-11-15): DevOps Directive, “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); MSec, “Highlight: Terraform Associate Exam Prep | Importing Existing Infrastructure into Terraform” (yECJjdXhojA); freeCodeCamp.org, “Terraform Course - Automate your AWS cloud infrastructure” (SLB_c_ayRMo); Christian Lempa, “Let's migrate from Terraform to OpenTofu!” (xstFUuFt5Q0); Fireship, “Terraform in 100 Seconds” (tomUWcQ0P3k); TechWorld with Nana, “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE). oEmbed does not return durations or publish dates, so durations are not shown on the cards. No verified dedicated videos were found for TF_LOG layered logs, state surgery, provider throttling, performance optimization, the Plugin Framework, or fault drills, so storyboard scripts are provided instead. All videos are in English and were recorded before Terraform 1.17; for new features, this hour and the official docs take precedence.
Voice narration note
The “Voice” page uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, with English terms pronounced in en-US. The result depends on the voices installed in the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; for offline audio, hand the narration script to a TTS service such as Azure AI Speech.
Known limitations
- The lab commands in this hour were not actually executed when written; the IDs, hashes, version IDs, times, durations, serial values, and PIDs in the “expected output” are sample values, and the actual values in your environment take precedence.
- The verbatim error messages are written in the typical wording of Terraform 1.17 / kreuzwerker/docker 4.7.0 / Docker Engine 29; some wording (for example the exact text of a docker_container health-wait failure, a port conflict, or a state load failure) varies by version, so when diagnosing, rely on the key terms.
- gRPC method names (such as
ValidateProviderConfig,ValidateDataResourceConfig) and log prefixes (GRPCProvider/GRPCProvider.v6) may vary slightly with the Terraform and protocol versions; the official docs state that JSON log fields are not stable. -minimal-refresh's semantic basis is the 1.17.0 release note “refresh only resources with proposed changes”; for how it determines “proposed changes” and how it differs from-refresh=falsein edge cases, follow the official plan command docs; the output in Lab 5 is illustrative.- The breaking changes of azurerm 5.0 are not verified item by item in this hour; please read the official upgrade guide. The AWS provider's log field names (such as
http.response.status_code,rpc.method) change with the SDK version. - The Plugin Framework sample code is written against the public v1.x interfaces and has not been compiled in this environment; if the interfaces change, compare with the official scaffolding-framework template. The minimum Go and Terraform versions follow the official tutorial.
- The durations, rate-limit parameters, and probabilities in the animations and simulators are illustrative values used to explain the mechanisms; they do not represent real performance.
faultbox.shDepends on GNU sed; on macOS you needgsed.