Terraform Hour 1: Core Fundamentals
- Explain declarative IaC the difference from imperative scripts, and make evidence-based choices among Terraform, OpenTofu, Pulumi, Bicep, CloudFormation, and Ansible.
- Understand Terraform's core + provider plugin architecture: core parses configuration and builds dependency graph, manages state; the provider is a separate process that communicates through gRPC (plugin protocol v5/v6) to implement
PlanResourceChange/ApplyResourceChangeand other calls. - Read and write fluently HCL:
terraform/provider/resource/data/variable/output/locals/moduleeight block types, expressions, functions, andforexpressions. - Use
required_providersversion constraints and.terraform.lock.hclthe lock file so that teams and CI get exactly the same provider, handle multi-platformproviders lock, plugin caching, and mirrors. - Master implicit/explicit dependencies and
lifecycle(create_before_destroy,prevent_destroy,ignore_changes,replace_triggered_by) as well as-replace. - Know state what it stores, why it is sensitive, and why it must not be edited by hand; use
state list/show,apply -refresh-onlyto handle drift. - Follow
fmt → validate → plan -out → apply plan filethe standard workflow, and use-detailed-exitcodefor CI drift detection, and diagnose the dozen or so most common error types.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (local Docker) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup | Install Terraform 1.17 on Ubuntu 24.04 (HashiCorp apt repository), and confirm Docker 29 and the myapp image | Environment self-check list | terraform version,docker info |
| 1 | 00–06 | IaC and Terraform Architecture | Declarative vs. imperative, tool comparison, core + provider gRPC, dependency graph, BSL and OpenTofu | The full mechanics of a single terraform apply (core animation) | Your first docker_container |
| 2 | 06–13 | HCL Syntax and Core Blocks | 8 block types, arguments and nested blocks, types, expressions, interpolation, comments, file organization conventions | HCL block dissector (click to highlight) | Split the stack into a standard file structure |
| 3 | 13–19 | Providers and the Lock File | required_providers, version constraint operators, init installation flow, lock file h1/zh hashes, multi-platform locks, caching and mirrors | Version constraint solver | Lock file + plugin cache |
| 4 | 19–27 | Resources, Dependencies, and Lifecycle | implicit/explicit dependencies, parallelism, create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by, -replace | Dependency graph and replacement-order simulator | Full nginx + myapp + redis stack |
| 5 | 27–34 | Variables, Outputs, Locals | type system, default values, validation, sensitive, nullable, tfvars precedence, TF_VAR_ | Variable precedence calculator | Switching between dev and prod tfvars |
| 6 | 34–41 | Data Sources and Expression Functions | when data blocks are read, common functions, for/splat/conditional expressions, dynamic blocks,terraform console | for expression lab | Automatically update images by digest |
| 7 | 41–50 | State Basics | the purpose and structure of state, serial/lineage, sensitive data, state list/show, refresh-only, and why not to edit by hand | Configuration · state · real world: three-way comparison (drift) | Create and fix drift |
| 8 | 50–60 | CLI Workflow and Troubleshooting Basics | init/fmt/validate/plan/apply/destroy, plan files,-detailed-exitcode, TF_LOG, common errors | CLI pipeline + interactive troubleshooting tree | CI-style plan/apply |
| — | After class | Cheat sheet · Comprehensive lab | Use Terraform to manage the complete local myapp stack, demonstrating drift and repair | Final quiz (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Labs |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain IaC and Terraform architecture | ✓ | · | ✓ | ✓ | · | · | ✓ | · | terraform graph,TF_LOG | M1 first container |
| Read and write HCL configuration | · | ✓ | · | ✓ | ✓ | ✓ | · | · | terraform fmt,validate | Refactor file structure |
| Manage provider versions and the lock file | · | · | ✓ | · | · | · | · | ✓ | init -upgrade,providers lock | Multi-platform lock |
| Model resource dependencies and lifecycle | ✓ | · | · | ✓ | · | ✓ | · | · | apply -replace,graph | Full stack + replacement |
| Parameterization and outputs | · | ✓ | · | · | ✓ | ✓ | · | · | -var-file,output -json | dev/prod |
| Query external data, write expressions | · | · | · | · | ✓ | ✓ | · | · | terraform console | Pull triggered by digest |
| Understand and inspect state | ✓ | · | · | · | ✓ | · | ✓ | ✓ | state list/show,show -json | drift |
| Drift detection and repair | · | · | · | ✓ | · | · | ✓ | ✓ | plan -refresh-only,-detailed-exitcode | Comprehensive lab |
| Standard CLI workflow and troubleshooting | · | · | ✓ | · | · | · | ✓ | ✓ | plan -out,apply tfplan | M8 lab |
Topics excluded from this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
remote backend (S3 + use_lockfile, azurerm), state locking, workspaces,import/moved/removed blocks, writing modules | Belongs to “Team collaboration and production readiness” | Lesson 2(simulating S3 with a MinIO container) |
| azurerm 5.x (latest 5.14.0), authentication, Container Apps / VMs | Requires a cloud subscription and incurs costs | Lesson 3 (Azure) |
| aws 6.x (latest 6.73.0), VPC, ECS Fargate | Same as above | Lesson 4 (AWS) |
GitHub Actions + OIDC, HCP Terraform, Terraform Policy (1.17 GA),terraform test | Belongs to automation and operations | Lesson 5 |
ephemeral resources, write-only arguments,check blocks, Stacks | Depends on the fundamentals in this lesson | Lessons 2, 5, 6 |
Performance tuning (-parallelism, splitting large state), in-depth troubleshooting | Requires a larger-scale environment | Lesson 7 |
How to use this courseware
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. We recommend reading “Principles” and “Animation” first, then doing the “Labs”. All labs need only local Docker and incur no cloud costs.
A quiz score of ≥ 70% or clicking “Mark module complete” counts toward progress, saved in this browser (if local storage is blocked, progress is cleared on refresh).
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration aloud; without a Chinese voice pack, the narration can still be read or passed to a TTS tool.
docker run, custom networks, named volumes, and the Flask + Redis sample app in it myapp (image myapp:1.0, port 5000). This lesson uses Terraform to turn these manual commands into declarative configuration.-minimal-refresh planning options (refresh only resources with proposed changes), Terraform Policy GA (-policies). The lab provider is kreuzwerker/docker 4.7.0 (2026-11-11; 4.0.0 released 2026-04-03, introducing the Plugin Framework hybrid service and building with buildx by default),hashicorp/random 3.9.1,hashicorp/local 2.9.1. The HCL syntax and CLI behavior covered in this lesson remain compatible within 1.x (the Terraform v1.x compatibility promise), so the labs can also be completed with 1.15/1.16.Module 0 · Environment setup (complete before class)
- Workstation: Ubuntu 24.04 LTS (an Azure VM, a local machine, or WSL2 all work), with Docker installed as in the Docker course Docker Engine 29, with the current user in the
dockergroup (so docker runs without sudo). - You have completed the myapp from the Docker course (
~/myapp, Flask + gunicorn + Redis counter). If you don't have it, that's fine: Step 3 rebuilds and adds it within 1 minute/healthz. - All lab directories for this lesson are under
~/tf-lab/; all resources are local Docker containers, networks, and volumes,so there are no cloud costs.
Step 1: Install Terraform from the official HashiCorp apt repository
The following commands match developer.hashicorp.com/terraform/install(verified 2026-11-15; the latest version on the page is 1.17.2): first import the HashiCorp GPG public key into a separate keyring, then add the repository for your distribution codename (the codename for Ubuntu 24.04 is noble).
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common wget wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg # Optional: verify the public key fingerprint (compare it with the fingerprint published on HashiCorp's official security page) gpg --no-default-keyring --keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg --fingerprint echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list sudo apt update && sudo apt install terraform
terraform version terraform -install-autocomplete # Install Tab completion for bash; takes effect after reopening the terminal
Terraform v1.17.2 on linux_amd64
apt-cache madison terraform list the available versions, then sudo apt install terraform=1.17.2-1, and use sudo apt-mark hold terraform to prevent it from being apt upgrade upgraded accidentally (the version suffix follows the madison output). Another option is a version manager such as tfenv or mise, which switches versions per directory; these are community tools, so install them following their official documentation. In the configuration, required_version (Module 3) is the last line of defense./var/run/docker.sock is available in WSL. Native Windows can use winget install Hashicorp.Terraform, but the commands in this lesson follow Linux bash.Step 2: Confirm Docker Engine
docker version --format 'client {{.Client.Version}} / server {{.Server.Version}}'
docker info --format '{{.OperatingSystem}} cgroup={{.CgroupVersion}}'
ls -l /var/run/docker.sock
id -nG | grep -qw docker && echo "in docker group" || echo "NOT in docker group"
client 29.x / server 29.x Ubuntu 24.04.3 LTS cgroup=2 srw-rw---- 1 root docker 0 Nov 15 08:00 /var/run/docker.sock in docker group
The Docker provider connects via /var/run/docker.sock to call the Docker Engine API (the same as the docker CLI). If you are not in the docker group: sudo usermod -aG docker $USER, then log in again. Note that the docker group is equivalent to root privileges; this is also discussed in the security section of Module 3.
Step 3: Prepare the myapp:1.0 image (with /healthz)
The same application as in the Docker course, with one addition: an /healthz endpoint that does not depend on Redis, so Terraform can configure a health check for the container. Anyone who already has myapp:1.0 is also advised to rebuild once to get /healthz.
mkdir -p ~/myapp && cd ~/myapp
cat > app.py <<'EOF'
import os, socket
from flask import Flask
import redis
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_connect_timeout=1)
@app.route("/")
def index():
try:
hits = r.incr("hits")
except redis.exceptions.ConnectionError:
hits = "N/A (redis not connected)"
return f"Hello from {socket.gethostname()}, hits={hits}\n"
@app.route("/healthz")
def healthz():
return "ok\n"
EOF
cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF
cat > Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m appuser
USER appuser
EXPOSE 5000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz')" || exit 1
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
EOF
docker build -t myapp:1.0 .
docker image ls myapp
REPOSITORY TAG IMAGE ID CREATED SIZE myapp 1.0 3f1c2a9b7d10 10 seconds ago 160MB
docker_image can also be used build {} block to build images (buildx by default since 4.0), but building artifacts is usually CI's job, while Terraform is responsible for “deploying infrastructure”. The main thread of this lesson treats myapp:1.0 as an artifact that already exists; the extension exercise in Module 4 demonstrates build blocks.Step 4: Clean up same-named objects left over from the Docker course (to avoid conflicts)
The container names in this lesson all carry the myapp-dev- prefix and generally won't conflict. If the Compose stack from the Docker course is still running, it will occupy ports 5000/8080:
cd ~/myapp && docker compose down 2>/dev/null; docker ps --format 'table {{.Names}}\t{{.Ports}}'
ss -ltnp | grep -E ':8080|:5000' || echo "8080/5000 free"
Warm-up: answer from memory (30 seconds)
In the Docker course, to let the app reach Redis by name, redis what manual steps are needed?
docker network create mynet → docker run --network mynet --name redis … → docker run --network mynet -e REDIS_HOST=redis …. The order matters (the network must exist first), and re-running it reports “name already in use”. This is exactly the problem that Terraform's dependency graph and “desired state” are meant to solve.
Is the Compose docker compose up file declarative or imperative? How does it differ from Terraform?
Compose is declarative (it describes the desired services), but it has no separate state file; it identifies ownership through container labels and can only manage containers on one Docker host. Terraform uses state to record the mapping from “configuration address ↔ real object ID”, and can manage any platform that has a provider (Docker, Azure, AWS, GitHub, DNS…).
Module 1 · IaC and Terraform Architecture
- Explain in your own words the difference between declarative (desired state) and imperative (step-by-step) approaches, as well as “convergence” and “idempotence”.
- Draw Terraform's architecture: CLI/core, state, provider plugin processes, and the target platform APIs; name the main gRPC calls between core and the provider.
- Describe a single
terraform applyfull run through the stages: load configuration → build the dependency graph → read and refresh state →PlanResourceChange→ show the plan →ApplyResourceChange→ write state. - Be able to justify a choice among Terraform / OpenTofu / Pulumi / Bicep / CloudFormation / Ansible.
What: what IaC is, and what Terraform is
Infrastructure as Code (IaC) is writing infrastructure such as networks, virtual machines, containers, DNS, and permissions as text files, stored in Git like application code, reviewed through code review, and executed automatically. Terraform is a declarative IaC tool developed by HashiCorp: you use HCL (HashiCorp Configuration Language) to describe the desired end state. Terraform compares the “configuration (desired)”, the “state (last recorded)”, and the “real world (read via refresh)”, computes the create/update/replace/delete operations needed, and executes them in dependency order.
| Imperative | Declarative | |
|---|---|---|
| You write | Steps: create the network first, then start redis, then start the app | Result: there should be 1 network, 1 redis, and 2 apps |
| Re-running | The second run reports “name already in use”, so you have to write your own if checks | With no differences, nothing is done (No changes) |
| Modifying | You have to write a script that deletes the old and creates the new | Change configuration → Terraform computes the diff (in-place update or replacement) |
| Deleting | You need a separate cleanup script, which is easy to get wrong | Remove the block from the configuration, or terraform destroy |
| Examples | bash + docker run,az/aws CLI scripts | Terraform, Bicep, CloudFormation, Kubernetes YAML, Compose |
Why: why Terraform is needed
- Reviewable:
terraform planGives an exact list of changes before execution (what will be replaced and what will be deleted), which can be pasted into a PR review. - Replayable: the same configuration plus the same lock file produces consistent results across dev/staging/prod; disaster recovery is simply re-applying.
- Automatic dependency ordering and parallelism: core builds a directed acyclic graph (DAG) from references; resources without dependencies are created in parallel, by default up to 10 at a time.
- One workflow manages multiple platforms: the Registry has thousands of providers (Azure, AWS, GCP, Kubernetes, Docker, GitHub, Cloudflare, Datadog…), all with the same plan/apply/state semantics.
- Drift is visible: if someone manually changes a resource in the console or on the command line, the next plan will show it (Module 7).
How: how Terraform works
Terraform consists of two parts:
- Terraform core (this is the
terraformbinary): parses HCL, evaluates expressions, builds the dependency graph, reads and writes state, computes diffs, schedules execution, and shows the plan. Core doesn't know any specific cloud or Docker; it only knows the “schema of resource types”. - Provider plugins: each provider is a separate executable (for example
terraform-provider-docker_v4.7.0), which isterraform initdownloaded into.terraform/providers/. At runtime, core starts it as a child process (HashiCorp go-plugin), and the two communicate over a local gRPC connection (plugin protocol v5 or v6, based on Protocol Buffers; the connection uses automatically generated mTLS certificates). The provider then calls the real APIs (Docker Engine API, Azure Resource Manager, AWS API…).
| gRPC call (implemented by the provider) | When called | Purpose |
|---|---|---|
GetProviderSchema | At the start of each command | Returns the schema of the provider/resource/data source (attributes, types, whether Computed/ForceNew) |
ValidateProviderConfig / ValidateResourceConfig | validate, plan | Validates arguments without calling the API |
ConfigureProvider | Before API access is needed | Passes in the provider block's configuration (such as the Docker host or cloud credentials), and the provider sets up its client |
UpgradeResourceState | After reading state | Upgrades state from an older schema version to the current schema |
ReadResource | Refresh phase | Reads real objects by the IDs in state and detects drift |
ReadDataSource | plan (or apply, depending on whether the arguments are known) | Runs data block queries |
PlanResourceChange | plan | Input: prior state + configuration + the proposed new state synthesized by core; output: planned state (unknown values marked as known after apply) and RequiresReplace paths |
ApplyResourceChange | apply | Actually calls the API to create/update/delete, returns the new state, which core writes to state |
ImportResourceState | import | Brings existing objects under management (Lesson 2) |
ephemeral resources (1.10+) also have OpenEphemeralResource/CloseEphemeralResource, and provider-defined functions (1.8+) have CallFunction, and list resources (terraform query) have ListResource and so on, which are covered in later lessons.
When: when to use Terraform and when not to
- Suited for: creating, changing, and destroying infrastructure objects (networks, clusters, database instances, DNS, IAM, SaaS configuration), especially in multi-environment, multi-cloud scenarios that require review.
- Not suited for: installing software inside a virtual machine or editing config files (hand these to Ansible / cloud-init / image builds); frequently changing application releases (hand these to CI/CD, Kubernetes controllers, GitOps); complex procedural orchestration (hand this to a workflow engine).
Comparison with similar tools (2026-11)
| Terraform | OpenTofu | Pulumi | Bicep | CloudFormation | Ansible | |
|---|---|---|---|---|---|---|
| Language | HCL | HCL (highly compatible with Terraform) | TS/Python/Go/C#/Java/YAML | Bicep DSL → ARM JSON | YAML/JSON | YAML playbook |
| Paradigm | Declarative | Declarative | Declarative results, written in an imperative language | Declarative | Declarative | Mainly procedural (the modules themselves are mostly idempotent) |
| State | state file (local / remote backend / HCP Terraform) | Same as left, and also supports client-side state encryption | Pulumi Cloud or a self-managed backend | No separate state; Azure deployment history; Deployment Stacks manage the lifecycle | AWS-managed stack | No state (queries the target machine every time) |
| Platform | Any (provider ecosystem) | Any (most providers are common) | Any | Azure only | AWS only | Any (leans toward configuration management) |
| License | BSL 1.1 (from 1.6) | MPL 2.0, a Linux Foundation project | Apache 2.0 (engine) | MIT | AWS services | GPL v3 |
| Typical uses | Multi-cloud infrastructure | Same as left, prefers an open-source license | Teams whose developers know general-purpose languages | Pure Azure teams | Pure AWS teams | System configuration, application deployment (the second course) |
Background: in 2023-08, HashiCorp changed Terraform's license from MPL 2.0 to BSL 1.1 (starting with 1.6), and the community then forked OpenTofu (currently 1.13.x, latest 1.13.9). IBM has completed its acquisition of HashiCorp (the official YouTube channel is now named “HashiCorp, an IBM Company”). The BSL restricts “offering a product that competes with HashiCorp”; using Terraform internally to manage your own infrastructure is not affected. For specific legal questions, rely on the license text and your company's legal advice.
azurerm_linux_virtual_machine ≠ aws_instance), so they must be written separately. ② “Terraform continuously monitors and automatically fixes drift”—no, it only compares when you run plan/apply; continuous reconciliation is the job of Kubernetes controllers or HCP Terraform's drift detection. ③ “The provider is part of core”—providers are separately released and separately versioned processes; upgrading Terraform does not upgrade providers, and vice versa. ④ “If the plan succeeds, the apply will succeed”—plan does not call create APIs, and errors such as port conflicts, quotas, or insufficient permissions often only surface during apply.Architecture diagram: core, state, provider plugins, and target APIs
Dependency graph: the DAG of this lesson's myapp stack
docker_network.app.id) derives edges; depends_on adds hidden dependenciesCore animation: a single terraform apply full run's mechanics
After selecting a scenario, click “Play” or “Next step”. Each step highlights the components involved; the terminal below shows what you would see in the TF_LOG=DEBUG logs, CLI output, or Docker API. The three scenarios correspond to the three most common kinds of apply: first creation, no changes, and the real world having drifted.
ApplyResourceChange return values, which are then passed on to downstream resources.Commands covered in this module
| Command | Purpose | Key options / notes |
|---|---|---|
terraform version | View the core and installed provider versions | -json (since 1.17, JSON includes format_version field) |
terraform init | Initialize the working directory: install providers and modules, configure the backend | Module 3 details |
terraform plan | Compute the execution plan (does not change real resources) | -out,-refresh-only,-destroy |
terraform apply | Plan + confirm + execute | -auto-approve,-parallelism=N (default 10) |
terraform graph | Output the dependency graph in DOT format | -type=plan; use with Graphviz dot -Tsvg |
TF_LOG=DEBUG terraform … | Output detailed logs (including plugin startup and gRPC calls) | TF_LOG_CORE / TF_LOG_PROVIDER controlled separately; TF_LOG_PATH Write to a file |
terraform version -json
{
"format_version": "1.0",
"terraform_version": "1.17.2",
"platform": "linux_amd64",
"provider_selections": {
"registry.terraform.io/kreuzwerker/docker": "4.7.0"
},
"terraform_outdated": false
}
Observe core starting the provider child process
cd ~/tf-lab/hello TF_LOG_CORE=DEBUG TF_LOG_PATH=./tf-debug.log terraform plan >/dev/null grep -E "starting plugin|plugin started|using plugin|plugin exited" tf-debug.log | head
[DEBUG] provider: starting plugin: path=.terraform/providers/registry.terraform.io/kreuzwerker/docker/4.7.0/linux_amd64/terraform-provider-docker_v4.7.0 args=[...] [DEBUG] provider: plugin started: path=.terraform/providers/registry.terraform.io/kreuzwerker/docker/4.7.0/linux_amd64/terraform-provider-docker_v4.7.0 pid=48213 [DEBUG] provider: using plugin: version=5 [DEBUG] provider: plugin exited
How to verify: Open another terminal while the command runs ps -ef | grep terraform-provider You can see the child process; it disappears after the command finishes. version=5 or 6 indicates the plugin protocol version (depends on the SDK the provider uses; the 4.x Docker provider mixes SDKv2 and Plugin Framework, presenting a unified protocol externally through mux). Common errors:TF_LOG=TRACE It outputs a large amount of information, including request bodies, which may contain sensitive data; do not paste it into a public issue. Production use: When troubleshooting an apply that is “stuck”, the logs show which resource's gRPC call core is still waiting on.
Output the dependency graph
terraform graph # DOT text sudo apt-get install -y graphviz && terraform graph | dot -Tsvg > graph.svg
digraph G {
rankdir = "RL";
node [shape = rect, fontname = "sans-serif"];
"docker_container.web" [label="docker_container.web"];
"docker_image.nginx" [label="docker_image.nginx"];
"docker_container.web" -> "docker_image.nginx";
}
Since 1.7 terraform graph The default output shows only a simplified graph of resources; to include internal nodes such as providers and variables in the full plan graph, use terraform graph -type=plan.
Lab 1: your first Terraform-managed container (about 5 minutes)
mkdir -p ~/tf-lab/hello && cd ~/tf-lab/hello
cat > main.tf <<'EOF'
terraform {
required_version = ">= 1.17.0"
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 4.7"
}
}
}
provider "docker" {
host = "unix:///var/run/docker.sock"
}
resource "docker_image" "nginx" {
name = "nginx:alpine"
keep_locally = true # do not delete the local image on destroy
}
resource "docker_container" "web" {
name = "hello-nginx"
image = docker_image.nginx.image_id # reference → implicit dependency
ports {
internal = 80
external = 8080
}
}
EOFterraform init
Initializing the backend... Initializing provider plugins... - Finding kreuzwerker/docker versions matching "~> 4.7"... - Installing kreuzwerker/docker v4.7.0... - Installed kreuzwerker/docker v4.7.0 (self-signed, key ID BD080C4571C6104C) ... Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository ... Terraform has been successfully initialized!
The key ID is a sample value; follow the actual output. “self-signed” means the provider was signed by its community author with their own GPG key (not an official HashiCorp signature); the Registry verifies the signature.
terraform plan
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# docker_container.web will be created
+ resource "docker_container" "web" {
+ id = (known after apply)
+ image = (known after apply)
+ name = "hello-nginx"
...
+ ports {
+ external = 8080
+ internal = 80
+ ip = "0.0.0.0"
+ protocol = "tcp"
}
}
# docker_image.nginx will be created
+ resource "docker_image" "nginx" {
+ id = (known after apply)
+ image_id = (known after apply)
+ keep_locally = true
+ name = "nginx:alpine"
+ repo_digest = (known after apply)
}
Plan: 2 to add, 0 to change, 0 to destroy.
image = (known after apply): the container depends on the image ID, which is only known after the image is pulled; this is the source of the “unknown values” in the plan.
terraform apply # type yes
curl -s localhost:8080 | grep -o '<title>.*</title>'
docker ps --filter name=hello-nginx --format '{{.Names}} {{.Image}} {{.Ports}}'
ls -la # terraform.tfstate appears
docker_image.nginx: Creating... docker_image.nginx: Creation complete after 4s [id=sha256:9a1b…nginx:alpine] docker_container.web: Creating... docker_container.web: Creation complete after 1s [id=7c3e5d…] Apply complete! Resources: 2 added, 0 changed, 0 destroyed. <title>Welcome to nginx!</title> hello-nginx sha256:9a1b… 0.0.0.0:8080->80/tcp
terraform apply
docker_image.nginx: Refreshing state... [id=sha256:9a1b…nginx:alpine] docker_container.web: Refreshing state... [id=7c3e5d…] No changes. Your infrastructure matches the configuration. Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
external = 8080 to 8081, then run terraform plan.
# docker_container.web must be replaced
-/+ resource "docker_container" "web" {
~ id = "7c3e5d…" -> (known after apply)
~ ports { # forces replacement
~ external = 8080 -> 8081 # forces replacement
# (3 unchanged attributes hidden)
}
}
Plan: 1 to add, 0 to change, 1 to destroy.
Docker does not support changing a running container's port mapping, so the provider marks the port setting in the schema ports as ForceNew,PlanResourceChange so the provider then returns RequiresReplace, and the plan shows -/+ (delete first, then create). Change the value back to 8080 before continuing.
terraform destroy # type yes docker ps -a --filter name=hello-nginx # no longer exists; the nginx:alpine image is kept because of keep_locally
Case 1: migrating from a “runbook + console clicks” to Terraform
Problem: One team's test environment was built by hand from a 40-step wiki; each rebuild took half a day, and dev/test/prod had many differences that “only one person knew”. Approach: Start with the resources that change most often and carry the lowest risk (network security group rules, DNS records), manage them with Terraform, and use an import block (Lesson 2) to bring existing resources under management; every change goes through a PR, and CI automatically posts the plan. Configuration: one set of tfvars plus a separate state for each environment. Limitations: Manual console changes are not allowed during adoption, otherwise drift will occur; pair this with Azure Policy / AWS SCP to tighten console write permissions.
Case 2: tool selection — Bicep or Terraform
Problem: A pure-Azure company was torn between Bicep and Terraform. Approach: After evaluation they chose Terraform, mainly because beyond Azure they also need to manage GitHub repositories and team permissions, Cloudflare DNS, and Datadog monitoring, all of which have official or partner providers. A purely Azure sub-team that wants zero state operations can keep using Bicep. Limitations: Terraform requires you to handle state storage, locking, and permissions yourself (Lesson 2); Bicep usually supports new Azure APIs on release day, while the azurerm provider may lag by a few weeks (the azapi provider can fill the gap; Lesson 3).
Case 3: what to do when half of an apply fails
Problem: apply creates 12 resources, and the 9th fails because of insufficient quota. Approach: No “rollback” is needed: the 8 resources that succeeded are already written to state. After fixing the quota, re-run terraform apply, and Terraform will create only the remaining resources. Limitations: Terraform has no transactional rollback; if a failed resource was partly created, the provider usually marks it as tainted, which is replaced on the next apply.
Common errors and fixes
Error: Error pinging Docker server: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
Cause: The Docker service is not running, or the provider's host points to the wrong socket (for example, the rootless Docker unix:///run/user/1000/docker.sock socket).
systemctl status docker --no-pager | head -5 docker context ls # show the endpoint the docker CLI is actually using echo $DOCKER_HOST
Fix:sudo systemctl start docker; or change the provider's host host to docker context ls the endpoint shown above (if host is not set, the provider reads the DOCKER_HOST environment variable).
Error: ... permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
Cause: The current user is not in the docker group, or was just added to the group but has not logged in again.
id -nG; ls -l /var/run/docker.sock
Fix:sudo usermod -aG docker $USER then log in again (or newgrp docker). Do not use sudo terraform— this creates root-owned .terraform/ and state files, which ordinary users can no longer read or write.
Error: Inconsistent dependency lock file / Error: Required plugins are not installed
Cause: You changed required_providers, or you cloned the repository without running terraform init.
Fix: Run terraform init; if you changed the version constraint, run terraform init -upgrade. See Module 3 for details.
Error: Unable to create container: Error response from daemon: Conflict. The container name "/hello-nginx" is already in use by container "…"
Cause: A container with the same name already exists in the real world but is not in the Terraform state (it may have been created by hand, or the state file was deleted). Terraform does not automatically “claim” existing objects.
docker ps -a --filter name=hello-nginx terraform state list
Fix: After confirming it can be deleted, run docker rm -f hello-nginx and retry; if it must be kept, use an import block to bring it into state (Lesson 2).
Error: Unable to start container: ... Bind for 0.0.0.0:8080 failed: port is already allocated
Cause: The host port is occupied by another container or process. The plan phase will not detect this. Note: at this point the container may have been created but not started, and the provider marks the resource as tainted.
ss -ltnp | grep 8080; docker ps --format '{{.Names}} {{.Ports}}' | grep 8080
Fix: Free the port or change external, then apply again (tainted resources will be replaced).
1. During an apply, confirm which provider process Terraform starts and which plugin protocol version it uses.
TF_LOG_CORE=DEBUG TF_LOG_PATH=tf.log terraform plan >/dev/null grep -E "plugin started|using plugin" tf.log # or while apply is running: ps -ef | grep terraform-provider
2. Generate an SVG of the dependency graph for the current configuration.
terraform graph | dot -Tsvg > graph.svg
A colleague says: “Terraform is too slow; I'll just write a bash script that loops over docker run.” Explain Terraform's value from four angles (idempotency, changes, deletion, and review), and point out when a bash approach is actually the better fit.
Bash fails on the second run because of duplicate names and needs many if checks; changing a port means hand-writing “delete the old, create the new”; deletion needs another cleanup script; changes cannot be previewed before execution. Terraform achieves idempotency with state + diff; plan gives precise changes (including replacements); deletion only requires removing the code. Conversely, for a one-off temporary experiment, or for steps executed inside a container (such as a data migration script), a script is simpler. Terraform manages the existence and configuration of objects, not the process.
Verified teaching videos
Official documentation
Video storyboard (about 90 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided; they can be passed to a video tool.
Scene: on the left, a bash script runs line by line, and on the second run a red “name already in use” appears; on the right, a main.tf shows a green “No changes” on the second run.
Narration: an imperative script describes steps; a declarative configuration describes the result. When run repeatedly, Terraform finds no differences and does nothing.
Scene: inside the terraform binary box, “parsing, dependency graph, state” appear; next to it a separate provider process pops up, connected by a line labeled gRPC.
Narration: Terraform core only understands configuration, the dependency graph, and state; each provider is an independent plugin process that accepts calls from core over gRPC and then calls the real API.
Scene: the dependency graph lights up from left to right: network and image turn green in parallel, then container turns green; each time one turns green, the serial in the state file goes up by one.
Narration: plan first, then execute. PlanResourceChange computes the differences, ApplyResourceChange calls the API, and each resource is written to state as it completes.
Scene: six cards (Terraform, OpenTofu, Pulumi, Bicep, CloudFormation, Ansible), each labeled with its language, state model, and platform.
Narration: for multi-cloud, choose Terraform or OpenTofu; for pure Azure, Bicep is an option; system configuration is handled by Ansible. Each tool has its own role.
Module 2 · HCL syntax and core blocks
- Identify blocks, labels, arguments, nested blocks, meta-arguments, and expressions.
- Name the purpose of the eight top-level block types:
terraform,provider,resource,data,variable,output,locals,module, as well asTYPE.NAMEthe reference rules for resource addresses. - Use string interpolation, heredocs, conditional expressions, and comments, and organize files according to the official style guide.
What: basic structure of HCL
HCL (HashiCorp Configuration Language) is a configuration language designed to be both human-readable and machine-parseable. A Terraform configuration is made up of blocks:
BLOCK_TYPE "LABEL_1" "LABEL_2" { # block type + 0 to 2 labels
argument_name = expression # argument: name = expression
nested_block { # nested block: no equals sign
another_argument = "value"
}
}
| Block | Label | Purpose | Reference |
|---|---|---|---|
terraform | None | Set by Terraform itself: required_version,required_providers,backend,cloud | — |
provider | provider local name | Configure the provider (API endpoint, region, credentials); can use alias to define multiple instances | provider = docker.remote |
resource | type, name | Declare an infrastructure object whose lifecycle is managed by Terraform | docker_container.redis.id |
data | type, name | Read-only query of existing external objects or computed results (Module 6) | data.docker_network.ext.id |
variable | name | Input parameters (Module 5) | var.env |
output | name | Output values, for people, parent modules, or other configurations | module.net.network_id (from the parent module) |
locals | None | Named intermediate values (you can have multiple locals blocks) | local.name_prefix (note: singular) |
module | name | Calls another set of configuration (local directory, Registry, Git) | module.web.url |
In addition, there are import,moved,removed,check (Lessons 2 and 5), and ephemeral,action,list and other newer block types, which later lessons introduce as needed.
Why: why HCL rather than YAML/JSON
- Has expressions: references, functions, conditionals,
forExpressions are first-class, so no extra template language is needed (compare CloudFormation's!Ref/!Sub). - Clear block structure: nested blocks correspond to sub-objects in the API,
terraform fmtcan be formatted uniformly. - Machine-generatable: every HCL has an equivalent JSON syntax (
*.tf.json), suitable for generating configuration programmatically.
How: a quick look at expressions
| Category | Syntax | Example |
|---|---|---|
| Primitive types | string / number / bool / null | "redis",6379,true,null (equivalent to “not writing this argument”) |
| Collections | list/tuple [ ], map/object { } | ["a", "b"],{ env = "dev", tier = "web" } |
| References | TYPE.NAME.ATTR,var.,local.,data.,module. | docker_image.redis.image_id |
| Special references | path.module,path.root,path.cwd,terraform.workspace,count.index,each.key/each.value,self | "${path.module}/nginx.conf.tftpl" |
| Interpolation | "${ … }" | "${var.project}-${var.env}-redis" |
| Template directives | %{ if } / %{ for } | "%{ if var.debug }-v%{ endif }" |
| Heredoc | <<EOT,<<-EOT (strip common indentation) | Multi-line configuration content |
| Operators | Arithmetic, comparison, logical && || ! | var.replicas > 1 |
| Conditional | cond ? a : b | var.env == "prod" ? 3 : 1 |
| Functions | name(args), only built-in functions and provider functions can be used | upper(var.env),merge(a, b) |
| for / splat | [for x in list : …],list[*].attr | Module 6 |
Difference between arguments, nested blocks, and meta-arguments
- Argument:
name = "x", defined by the provider schema (docker_container'sname,image,env…). - Nested block:
ports { … }, also defined by the schema, and can appear multiple times (one block per port mapping). It cannot be written asports = { … }. - Meta-argument: defined by Terraform core and common to all resources:
count,for_each,depends_on,provider,lifecycle(Module 4).
Comments and file organization
- Comments:
#single-line (recommended by the style guide),//single-line,/* … */multi-line. - All
.tf/.tf.jsonfiles in the same directory form a single module, with no loading order, and block order doesn't matter either; subdirectories are not loaded automatically (you must call them with amoduleblock). - Files recommended by the official style guide:
terraform.tf(orversions.tf) hold the terraform block;providers.tf;main.tf(or split by domain intonetwork.tf,redis.tf);variables.tf;outputs.tf;locals.tf;backend.tf. - Naming: resource names use lowercase with underscores (for example
redis_data), do not repeat the type (writedocker_network.app, notdocker_network.app_network; indent arguments by 2 spaces and align equals signs at the same level (handled byterraform fmt). override.tf/*_override.tfoverride files are merged last and override the arguments of same-named blocks. This is rarely used, and it confuses readers.
When: which structure to use when
- The same value appears more than twice → extract it into
locals; the user needs to change it →variable; it needs to be visible externally →output. - A group of resources repeats across multiple projects →
module(Lesson 2). - Want to read an object that is “not mine” →
data; to create or manage it →resource.
Comparison with similar technologies
| HCL (Terraform) | Bicep | CloudFormation YAML | Pulumi | |
|---|---|---|---|---|
| References | docker_network.app.id | vnet.id | !Ref / !GetAtt | object attributes net.id (Output type) |
| Loops | count / for_each / for | [for … ] | Limited (macros / Fn::ForEach) | Native language loops |
| Custom functions | Not supported (only built-in and provider functions) | Supports user-defined functions | None | Native language |
| Formatting tool | terraform fmt | bicep format | cfn-lint | Built into the language |
locals Writing locals.x references in a block”—define with locals { }, reference with local.x. ③ “Nested blocks are map arguments”—ports { } are blocks, while labels = { } such as these are the map arguments; writing them incorrectly gives “Unsupported argument” or “Unsupported block type”. ④ “${} Must be wrapped in ${} everywhere”—since 0.12 you write the reference directly image = docker_image.redis.image_id, and interpolation is only needed when concatenating strings.Block anatomy diagram
File organization: one directory is one module
.terraform/ and state must not be committedInteractive: HCL block dissector
Click any highlighted fragment in the code, or use the “explain one by one” button to step through them. The panel on the right explains which syntactic element it belongs to, who interprets it (HCL parser / Terraform core / provider schema), and what core does during evaluation.
Syntax-related commands
| Command | Purpose | Key options |
|---|---|---|
terraform fmt | Format the .tf/.tfvars in the current directory to the canonical style | -recursive,-check (for CI; returns non-zero when differences exist),-diff |
terraform validate | syntax + type + schema validation (no API access, does not read state) | -json; requires init first (needs the provider schema) |
terraform console | Evaluate expressions interactively | Module 6 |
terraform providers schema -json | Export the schema of all resources | Authoritative source for looking up argument names and whether they are ForceNew |
cd ~/tf-lab/myapp-stack terraform fmt -check -diff # check only, do not modify terraform fmt # actually format; prints the names of modified files terraform validate
--- old/redis.tf
+++ new/redis.tf
@@ -1,4 +1,4 @@
resource "docker_container" "redis" {
- name = "${local.name_prefix}-redis"
- image= docker_image.redis.image_id
+ name = "${local.name_prefix}-redis"
+ image = docker_image.redis.image_id
redis.tf
Success! The configuration is valid.
Query resource schemas (argument names follow this)
terraform providers schema -json \ | jq '.provider_schemas["registry.terraform.io/kreuzwerker/docker"].resource_schemas.docker_container.block.attributes | keys | length' terraform providers schema -json \ | jq '.provider_schemas["registry.terraform.io/kreuzwerker/docker"].resource_schemas.docker_container.block.block_types | keys'
87 [ "capabilities", "devices", "healthcheck", "host", "labels", "mounts", "networks_advanced", "ports", "upload", "volumes", ... ]
How to verify:block_types names must be written as nested blocks,attributes and names are written as arguments. Common errors: validate requires terraform init first, otherwise it reports “Missing required provider”. Production use: The first step in CI is to run terraform fmt -check -recursive and terraform validate, catching format and syntax errors within seconds.
Lab 2: set up the standard file structure of the myapp-stack project (about 6 minutes)
This project runs through the rest of this lesson: this module creates the network, volumes, and Redis; Module 4 adds myapp and nginx; Module 5 parameterizes; Module 6 introduces data sources and templates; Modules 7 and 8 practice state and workflows.
mkdir -p ~/tf-lab/myapp-stack && cd ~/tf-lab/myapp-stack
cat > versions.tf <<'EOF'
terraform {
required_version = ">= 1.17.0, < 2.0.0"
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 4.7"
}
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}
EOF
cat > providers.tf <<'EOF'
provider "docker" {
host = "unix:///var/run/docker.sock"
}
EOF
cat > .gitignore <<'EOF'
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log
EOFcat > variables.tf <<'EOF'
variable "project" {
description = "Project name, used as the prefix for all Docker object names"
type = string
default = "myapp"
}
variable "env" {
description = "Environment name: dev or prod"
type = string
default = "dev"
}
EOF
cat > locals.tf <<'EOF'
locals {
name_prefix = "${var.project}-${var.env}" # myapp-dev
common_labels = {
project = var.project
env = var.env
managed_by = "terraform"
}
}
EOFcat > network.tf <<'EOF'
resource "docker_network" "app" {
name = "${local.name_prefix}-net"
driver = "bridge"
ipam_config {
subnet = "10.20.0.0/24"
}
}
resource "docker_volume" "redis_data" {
name = "${local.name_prefix}-redis-data"
}
EOF
cat > redis.tf <<'EOF'
resource "docker_image" "redis" {
name = "redis:7-alpine"
keep_locally = true
}
resource "docker_container" "redis" {
name = "${local.name_prefix}-redis"
image = docker_image.redis.image_id
restart = "unless-stopped"
command = ["redis-server", "--appendonly", "yes"]
networks_advanced {
name = docker_network.app.id
aliases = ["redis"] # myapp accesses it via REDIS_HOST=redis
}
volumes {
volume_name = docker_volume.redis_data.name
container_path = "/data"
}
# dynamic block: expands a map into multiple labels nested blocks (see Module 6 for details)
dynamic "labels" {
for_each = local.common_labels
content {
label = labels.key
value = labels.value
}
}
}
EOFcat > outputs.tf <<'EOF'
output "network_name" {
description = "Application network name"
value = docker_network.app.name
}
output "redis_container" {
value = docker_container.redis.name
}
EOF
terraform init && terraform fmt && terraform validate
terraform apply -auto-approve # for labs only; in production, plan first and review
Plan: 4 to add, 0 to change, 0 to destroy. docker_network.app: Creating... docker_volume.redis_data: Creating... docker_image.redis: Creating... docker_volume.redis_data: Creation complete after 0s [id=myapp-dev-redis-data] docker_network.app: Creation complete after 0s [id=b81c4f…] docker_image.redis: Creation complete after 3s [id=sha256:5e2f…redis:7-alpine] docker_container.redis: Creating... docker_container.redis: Creation complete after 1s [id=9d4a2e…] Apply complete! Resources: 4 added, 0 changed, 0 destroyed. Outputs: network_name = "myapp-dev-net" redis_container = "myapp-dev-redis"
Note that the first three resources are created in parallel— there are no references between them; the container waits until all three finish.
docker inspect myapp-dev-redis --format '{{json .Config.Labels}}' | jq .
docker exec myapp-dev-redis redis-cli ping
terraform output
terraform output -raw network_name
{
"env": "dev",
"managed_by": "terraform",
"project": "myapp"
}
PONG
network_name = "myapp-dev-net"
redis_container = "myapp-dev-redis"
myapp-dev-netnetworks_advanced { … } to networks_advanced = { … }, run terraform validate, read the error, then change it back. Do not clean up; Module 4 continues to use this project.Case 1: a thousand-line main.tf is hard to review
Problem: One repository had a single 1,800-line main.tf; every PR kept conflicting, and reviewers could not find the context of the changes. Approach: Split it by domain into network.tf,compute.tf,dns.tf,iam.tf, with variables and outputs gathered in variables.tf/outputs.tf; extract repeated structures into modules. Configuration: Pure file splitting does not change resource addresses; terraform plan showing No changes proves the refactor is safe. Limitations: Moving resources into a module changes their addresses (module.x.docker_container.y), which requires a moved block (Lesson 2); otherwise they will be planned as delete + recreate.
Case 2: CI catches formatting issues
Problem: Different IDEs' formatting styles produced diff noise. Approach: Run the format check as the terraform fmt -check -recursive first CI step; locally, use a pre-commit hook (community project pre-commit-terraform) to run fmt automatically before each commit. Limitations: fmt only handles formatting, not naming and structure; conventions need to be agreed on by the team or checked with tools such as TFLint.
Case 3: machine-generated configuration
Problem: The platform team needs to generate configuration from 300 firewall rules in the CMDB. Approach: Prefer a for expression for_each to iterate over a data structure produced by jsondecode(file("rules.json")) reading the file; only when the structures differ enormously should you generate *.tf.json. Limitations: Generated JSON is not convenient for human review, so always attach the plan output to the PR.
Common errors and fixes
Error: Unsupported argument — An argument named "networks_advanced" is not expected here. Did you mean to define a block of type "networks_advanced"?
Cause: A nested block was written in the name = { } form.
Fix: Remove the equals sign: networks_advanced { … }. Conversely, writing a map argument as a block gives “Unsupported block type”. Use terraform providers schema -json to check whether it is an attribute or a block_type.
Error: Missing required argument — The argument "name" is required, but no definition was found.
Cause: A Required argument in the schema was not written.
Fix: Check the “Argument Reference” in the Registry docs; Required arguments must be provided.
Error: Reference to undeclared resource — A managed resource "docker_image" "redis_img" has not been declared in the root module.
Cause: A typo, or the resource is in a subdirectory (subdirectories are not loaded automatically).
grep -n 'resource "docker_image"' *.tf
Fix: Correct the name; cross-module references must go through the module's output.
Error: Duplicate resource "docker_container" configuration — A docker_container resource named "redis" was already declared at redis.tf:6,1-36.
Cause: When splitting files, the same block was copied, and within one module TYPE.NAME must be unique.
Fix: Delete the duplicate block or rename it (renaming causes replacement, so use a moved block).
Error: Invalid character / Argument or block definition required
Cause: Commonly caused by copying Chinese curly quotes “ ” or full-width spaces from a web page, or by a missing closing brace.
grep -nP '[\x{201C}\x{201D}\x{3000}]' *.tfFix: Replace them with ASCII quotes and spaces, then run terraform fmt (fmt refuses to format on syntax errors and reports the line number).
1. Check the format of the entire repository (including subdirectories) in CI, and fail the pipeline if there are differences.
terraform fmt -check -recursive -diff
2. Without running apply, confirm that the docker_container 's ports is a nested block rather than an argument.
terraform providers schema -json | jq '.provider_schemas["registry.terraform.io/kreuzwerker/docker"].resource_schemas.docker_container.block.block_types.ports'
A new colleague put locals.tf in a config/ subdirectory “for easier management”, and validate reports “Reference to undeclared local value”. Explain the cause and give two fixes.
Terraform only loads the .tf files in the current directory; a subdirectory is not part of the same module. Fix 1: move the file back to the root directory (any file name works). Fix 2: move it into a real module config/ and call it with module "config" { source = "./config" } a module block, exposing values through output (module.config.name_prefix). For constant-only cases, Fix 1 is simpler.
Verified teaching videos
Official documentation
Video storyboard (about 75 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: one resource block, with colored boxes highlighting in turn the “block type”, the “two labels”, and the “braced body”.
Narration: in HCL, everything is a block. A resource block has two labels: the first is the type, whose prefix determines which provider handles it; the second is the name you choose.
Scene: in the body, the “name = sign” is highlighted green as an argument, and the “ports { braces }” are highlighted yellow as a nested block; a wrong form where ports has an equals sign with braces is crossed out in red.
Narration: arguments use an equals sign; nested blocks have no equals sign. If you get it backwards, validate will tell you right away.
Scene: several .tf files fly into one folder and merge into one large block; subdirectories are blocked from joining.
Narration: all tf files in the same directory form one module, in no particular order; subdirectories must be called with a module block.
Module 3 · Providers and the Lock File
- Write a correct
required_providers: local name,sourceaddress ([hostname/]namespace/type),versionconstraints, andrequired_version. - Explain
terraform initthe provider installation process (Registry discovery → download → GPG signature and checksum verification → extract to.terraform/providers). - Read
.terraform.lock.hclinh1:andzh:hashes, and useinit -upgradeto upgrade, andproviders lock -platformto fill in hashes for multiple platforms. - Configure the plugin cache
TF_PLUGIN_CACHE_DIRandprovider_installation(filesystem mirror / network mirror), to cope with offline and restricted network environments.
What: provider identity and version
terraform {
required_version = ">= 1.17.0, < 2.0.0" # constrains Terraform core itself
required_providers {
docker = { # local name: the resource type prefix docker_ and the provider "docker" block both use it
source = "kreuzwerker/docker" # source address = registry.terraform.io/kreuzwerker/docker
version = "~> 4.7" # version constraint: >= 4.7.0 and < 5.0.0
}
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}
- Source address format
[HOSTNAME/]NAMESPACE/TYPE; when the hostname is omitted, the default isregistry.terraform.io; a private Registry (such as the HCP Terraform private registry) requires the full hostname. - Local name is unique within a module and usually equals TYPE. Every module that uses a provider (including child modules) should declare its own
required_providers— otherwise Terraform will assumehashicorp/<local name>, which fordockermeans it will look for a non-existenthashicorp/docker(item 1 in the troubleshooting section).
Version constraint operators
| Syntax | Meaning | When to use |
|---|---|---|
= 4.7.0 or 4.7.0 | Exact version (the only way to match a pre-release version) | Temporarily pin to reproduce a problem |
!= 4.6.0 | Exclude a specific defective version | Combine with other conditions |
> >= < <= | Compare | Set the minimum version for a reusable module >= 4.0 |
~> 4.7 | Pessimistic constraint: only the rightmost segment is allowed to increase → >= 4.7.0, < 5.0.0 | Recommended for root modules: accept minor version updates, reject major versions |
~> 4.7.0 | >= 4.7.0, < 4.8.0 (accept patches only) | Conservative production environments |
>= 4.5, < 4.7, != 4.5.1 | A comma means “and” | Fine-grained control |
Why: why the lock file is needed
A constraint only gives a range. Without a lock file, if you run init today and get 4.7.0, a colleague running init next month may get 4.9.0, and CI may get yet another version — the same configuration then produces different plans. Dependency lock file .terraform.lock.hcl (introduced in 0.14) records, for each provider, the version actually selected and package hashes: later init runs install the same version and verify that the downloaded package matches the hashes (preventing tampering and supply-chain attacks). The lock file must be committed to Git.
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/kreuzwerker/docker" {
version = "4.7.0"
constraints = "~> 4.7"
hashes = [
"h1:Qm3x…=",
"zh:0a1b…",
"zh:1c2d…",
"zh:…",
]
}
zh:(zip hash): when a provider is published, the officialSHA256SUMSfile contains the SHA-256 of each platform's zip package. During init, it is obtained from the Registry for all platforms zh values.h1:(hash scheme 1): a hash computed over the contents of the extracted package directory. init computes h1 only for the current platform. To add h1 for other platforms, useterraform providers lock -platform=….- The lock file locks only providers, not module versions (module versions are pinned in the
moduleblock'sversion).
How: terraform init the provider installation process
- Collect the
required_providersfrom the root module and all child modules, and merge the constraints. - If the lock file already has the provider and its version satisfies the constraint → use the locked version directly (even if a newer version exists); adding
-upgradere-selects the latest version that satisfies the constraint. - Service discovery:
GET https://registry.terraform.io/.well-known/terraform.jsongets theproviders.v1path;GET /v1/providers/kreuzwerker/docker/versionslist versions and platforms. GET /v1/providers/kreuzwerker/docker/4.7.0/download/linux/amd64returns the zip download URL,SHA256SUMS, its GPG signature, and the signing public key.- Verify SHA256SUMS signature → verify zip hash → compare with the hash already in the lock file → extract to
.terraform/providers/registry.terraform.io/kreuzwerker/docker/4.7.0/linux_amd64/. - Write or update the lock file.
Caching and mirrors
- Plugin cache: set
TF_PLUGIN_CACHE_DIR(or in the CLI configuration file~/.terraformrcunderplugin_cache_dir). Multiple working directories share downloaded packages, saving time and bandwidth. When a lock file exists, a cached package must match the lock file's hashes to be used. - Mirror: in the CLI configuration, the
provider_installationblock can specifyfilesystem_mirror(a local directory, generated withterraform providers mirror),network_mirror(an HTTPS mirror service), anddirect(direct connection to the origin Registry), and useinclude/excludeto precisely control which provider is installed from where. Suited for offline data centers and enterprise environments with controlled outbound access.
When: best practices
- Root module:
version = "~> X.Y"+ commit the lock file; upgrading a provider is a separate PR (init -upgrade→ lock file diff + plan result). - Reusable module: only write the minimum version
>= X.Y, and do not commit the lock file (it is locked by the caller's root module). - When developers use macOS/Windows and CI uses Linux: use
providers lockto write hashes for all platforms at once, avoiding CI checksum mismatch errors. - Since 1.17, provider requirements can reference variable and local (for example, to manage version numbers centrally). Because the provider must be determined at init time, the referenced values must be known at init. For specific restrictions, follow the official documentation. This lesson still uses literal values.
Comparison with similar technologies
| Terraform | npm | Python pip | Go modules | |
|---|---|---|---|---|
| Range declaration | required_providers.version | package.json ^1.2 | requirements.in | go.mod |
| Locked | .terraform.lock.hcl (version + multi-platform hashes) | package-lock.json | pip-tools / uv lock | go.sum |
| Upgrade | init -upgrade | npm update | pip-compile -U | go get -u |
~> 4.7 only allow 4.7.x”—wrong: it allows anything from 4.7.0 up to but not including 5.0.0; to allow only patches, write ~> 4.7.0. ② “The lock file is generated automatically, so there's no need to commit it”—without committing it you lose reproducibility and hash verification. ③ “Upgrading Terraform also upgrades providers”—no, the two are independent. ④ “Write the version in the provider block”—old syntax, now deprecated; the version should be written in required_providers.Data flow for installing providers during init
Multi-platform locks: why a lock file generated on macOS may fail on Linux CI
Interactive: version constraint solver + lock file
Enter a version constraint (supports = != > >= < <= ~>, a comma means “and”), choose the version in the lock file, then click terraform init or terraform init -upgrade to see which version Terraform selects and why. The version list contains some published versions of kreuzwerker/docker.
Provider-related commands
| Command | Purpose | Key options / notes |
|---|---|---|
terraform init | Install providers/modules, initialize the backend, create or verify the lock file | -upgrade,-lockfile=readonly (CI: fails directly when the lock file would need to change),-backend=false |
terraform providers | Shows the providers and constraints each module requires, as a tree | Find out “who requires this provider” |
terraform providers lock | Compute and write hashes for the specified platforms | -platform=linux_amd64 can be repeated; -fs-mirror/-net-mirror |
terraform providers mirror DIR | Download the providers needed by the current configuration into a directory, for use by filesystem_mirror | -platform=… |
terraform version | Show the selected provider versions | requires init first |
cd ~/tf-lab/myapp-stack terraform providers cat .terraform.lock.hcl find .terraform/providers -maxdepth 5 -type d | tail -4
Providers required by configuration:
.
├── provider[registry.terraform.io/kreuzwerker/docker] ~> 4.7
└── provider[registry.terraform.io/hashicorp/random] ~> 3.9
Providers required by state:
provider[registry.terraform.io/kreuzwerker/docker]
…
.terraform/providers/registry.terraform.io/hashicorp/random/3.9.1/linux_amd64
.terraform/providers/registry.terraform.io/kreuzwerker/docker/4.7.0/linux_amd64
Write hashes for all platforms in the team
terraform providers lock \ -platform=linux_amd64 -platform=linux_arm64 \ -platform=darwin_arm64 -platform=windows_amd64 git diff --stat .terraform.lock.hcl
- Fetching kreuzwerker/docker 4.7.0 for linux_amd64... - Retrieved kreuzwerker/docker 4.7.0 for linux_amd64 (self-signed, key ID BD080C4571C6104C) - Fetching kreuzwerker/docker 4.7.0 for linux_arm64... … Success! Terraform has updated the lock file.
Plugin cache
mkdir -p ~/.terraform.d/plugin-cache echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache" rm -rf .terraform && time terraform init >/dev/null # first run: download and place in the cache rm -rf .terraform && time terraform init >/dev/null # second run: linked from the cache, noticeably faster ls -l .terraform/providers/registry.terraform.io/kreuzwerker/docker/4.7.0/
How to verify: The second init prints “Using kreuzwerker/docker v4.7.0 from the shared cache directory”,.terraform/providers/… the entries below are symbolic links pointing to the cache. Common errors: The cache directory must already exist. Production use: CI runners make the cache directory a persistent volume or use actions/cache, which can cut init time from tens of seconds to a few seconds.
Mirror configuration (restricted network / offline environments)
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"
provider_installation {
filesystem_mirror {
path = "/opt/terraform/providers"
include = ["registry.terraform.io/kreuzwerker/*", "registry.terraform.io/hashicorp/*"]
}
direct {
exclude = ["registry.terraform.io/kreuzwerker/*", "registry.terraform.io/hashicorp/*"]
}
}
# On a machine with internet access, prepare the mirror directory, then copy it to the offline environment terraform providers mirror -platform=linux_amd64 /opt/terraform/providers
Lab 3: lock file, upgrades, and multi-platform hashes (about 5 minutes)
cd ~/tf-lab/myapp-stack grep -A3 'provider "registry' .terraform.lock.hcl terraform version
provider "registry.terraform.io/hashicorp/random" {
version = "3.9.1"
constraints = "~> 3.9"
…
provider "registry.terraform.io/kreuzwerker/docker" {
version = "4.7.0"
constraints = "~> 4.7"
Terraform v1.17.2
on linux_amd64
+ provider registry.terraform.io/hashicorp/random v3.9.1
+ provider registry.terraform.io/kreuzwerker/docker v4.7.0version = ">= 4.0", then run terraform init.
- Reusing previous version of kreuzwerker/docker from the dependency lock file - Using previously-installed kreuzwerker/docker v4.7.0
Even if the constraint allows more versions, the locked 4.7.0 continues to be used.
version = "~> 4.5.0" (only allows 4.5.x), then run terraform init.
Error: Failed to query available provider packages Could not retrieve the list of available versions for provider kreuzwerker/docker: locked provider registry.terraform.io/kreuzwerker/docker 4.7.0 does not match configured version constraint ~> 4.5.0; must use terraform init -upgrade to allow selection of new versions
terraform init -upgrade grep -A2 'kreuzwerker/docker' .terraform.lock.hcl
- Finding kreuzwerker/docker versions matching "~> 4.5.0"...
- Installing kreuzwerker/docker v4.5.0...
provider "registry.terraform.io/kreuzwerker/docker" {
version = "4.5.0"
constraints = "~> 4.5.0"
Before downgrading a provider, confirm that the state's schema version is compatible (when a downgrade crosses a schema change, you get “resource instance managed by newer provider version”). There is no such issue between 4.5 and 4.7 here, but be careful in production.
sed -i 's/version = "~> 4.5.0"/version = "~> 4.7"/' versions.tf terraform init -upgrade terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 grep -c '"h1:' .terraform.lock.hcl # number of h1 entries increases
rm -rf .terraform && terraform init -lockfile=readonly && echo "lockfile OK" terraform plan # should show No changes
Case 1: a minor provider upgrade caused resources to be replaced
Problem: A team wrote the constraint as >= 3.0 and did not commit the lock file; one day CI automatically installed a new provider version, and the plan showed many “must be replaced”. Approach: Change it to ~> X.Y and commit the lock file. Provider upgrades become PRs opened automatically by Renovate/Dependabot (both support Terraform lock files), with the plan attached to the PR; merge only after confirming there are no unexpected replacements. Limitations: Even minor versions may change default values; always read the provider CHANGELOG.
Case 2: mixed-platform team
Problem: Developers use Apple Silicon Macs, CI uses Linux, and the ops jump host is Windows; every time someone runs init, the lock file changes. Approach: Provide a make lock in the repository's Makefile, using providers lock to write hashes for 4 platforms at once; CI uses -lockfile=readonly. Limitations: Some providers do not publish binaries for every platform (for example, no windows_arm64 package), so the lock command fails and that platform must be dropped.
Case 3: offline environment in the financial industry
Problem: The production network prohibits access to the public Registry. Approach: On a build machine in the DMZ, use terraform providers mirror to generate a mirror directory; after a security scan, sync it to the internal artifact repository; on internal machines, configure the ~/.terraformrc configuration network_mirror or filesystem_mirror, and exclude remove direct. Limitations: Mirrors are not updated automatically, so the upgrade process must go through change management; the lock file hashes still apply, so tampered packages in the mirror will be detected.
Common errors and fixes
Error: Failed to query available provider packages — provider registry registry.terraform.io does not have a provider named registry.terraform.io/hashicorp/docker
Cause: A module (commonly a child module) uses the docker_* resources, but has not declared the provider in its own required_providers block source = "kreuzwerker/docker", so Terraform infers by default hashicorp/docker (which does not exist).
terraform providers # find out which module requires hashicorp/docker grep -rn "required_providers" --include=*.tf .
Fix: Add required_providers { docker = { source = "kreuzwerker/docker" } } in that module.
Error: Inconsistent dependency lock file — provider registry.terraform.io/hashicorp/random: required by this configuration but no version is selected
Cause: The configuration added a new provider, but the lock file does not contain it, and init has not been run (or was run in -lockfile=readonly instead).
Fix: run terraform init (if necessary, -upgrade), then commit the updated lock file.
Error: Failed to install provider — the local package for registry.terraform.io/kreuzwerker/docker 4.7.0 doesn't match any of the checksums previously recorded in the dependency lock file
Cause: The lock file lacks the h1 hash for the current platform (it was generated on another platform), and the current package comes from a cache or filesystem mirror; in rare cases, the package was tampered with or the cache is corrupted.
grep -c '"h1:' .terraform.lock.hcl; uname -sm
Fix: Run in a trusted network terraform providers lock -platform=<current platform> to fill in the hashes; if you suspect cache corruption, delete that version's directory from the cache and retry. Do not manually delete hashes from the lock file to “work around” the problem.
Error: Incompatible provider version — Provider registry.terraform.io/xxx v1.2.3 does not have a package available for your current platform, linux_arm64.
Cause: This provider version did not publish a binary for the current platform.
Fix: Switch to a version that supports this platform, or run Terraform on an amd64 machine or container.
Error: Failed to query available provider packages — could not connect to registry.terraform.io: … dial tcp: lookup registry.terraform.io: i/o timeout
Cause: DNS, proxy, or firewall issue.
curl -sI https://registry.terraform.io/.well-known/terraform.json | head -1 env | grep -i proxy
Fix: Set HTTPS_PROXY; or configure the plugin cache or mirror (see the “Commands” page).
1. Make the lock file contain h1 hashes for both linux_amd64 and darwin_arm64.
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64
2. Initialize in CI: fail if the lock file needs changing, and do not configure a backend (validate only).
terraform init -lockfile=readonly -backend=false && terraform validate
A colleague's submitted PR changed only one line version = "~> 4.7" → "~> 4.8", but did not update the lock file. What happens in CI? What should a correct upgrade PR contain?
The locked 4.7.0 does not satisfy ~> 4.8, so CI's init reports an error asking for -upgrade (in readonly mode it fails directly). A correct upgrade PR should include: the version constraint change + terraform init -upgrade after running it, the updated lock file (with hashes for all team platforms) + the plan results for each environment (confirming no unexpected replacements) + a description of breaking changes in the provider CHANGELOG.
Verified teaching videos
No short, verified video specifically explaining dependency lock files was found; follow the official documentation and the storyboard below.
Official documentation
- Provider Requirements
- Version Constraints
- Dependency Lock File
- CLI Configuration File (plugin cache, provider_installation)
- terraform providers lock
Video storyboard (about 80 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: a version number line from 3.6 to 5.0,
~> 4.7 covering the range from 4.7.0 up to, but not including, 5.0.Narration: a version constraint gives a range. The wavy arrow only lets the rightmost segment grow: 4.7 allows anything up to but not including 5, while 4.7.0 allows only patches.
Scene: the lock file is like a lock clamped onto 4.7.0; a newer version appears beside it, grayed out; after pressing -upgrade, the lock moves.
Narration: the lock file records the version actually selected and its hashes. As long as the locked version satisfies the constraint, init keeps using it; to upgrade, you must explicitly add upgrade.
Scene: three machines (Mac, Linux, Windows), each with its own h1 line appearing in the lock file.
Narration: multi-platform teams should use providers lock to write hashes for all platforms at once, and commit the lock file to Git.
Module 4 · Resources, Dependencies, and Lifecycle
- Distinguish implicit dependencies (expression references) from explicit dependencies (
depends_on), and know when the latter must be used and the cost of overusing it. - Read the action symbols in a plan:
+create,~update in place,-/+destroy then create,+/-create then destroy,-delete,<=read data sources. - Use correctly:
lifecycle:create_before_destroy,prevent_destroy,ignore_changes,replace_triggered_by, andprecondition/postcondition. - Use
terraform apply -replace=ADDRto force replacement of a single resource (replacing the deprecatedterraform taint), and usecountto create multiple instances.
What: resources and dependencies
A resource block declares a (or a group when using count/for_each ), an object managed by Terraform. The order between resources is determined by dependencies:
- Implicit dependency: an expression references an attribute of another resource (
image = docker_image.redis.image_id). This is the preferred approach: data flow is dependency, which is accurate and self-explanatory. - Explicit dependency
depends_on = [docker_container.redis]: resource A needs B to exist first, but A's arguments do not reference any attribute of B. A typical example: myapp reaches Redis by DNS nameredisand the configuration contains only the stringREDIS_HOST=redis, so Terraform cannot see this relationship; in the cloud, a common case is “IAM permissions must be granted before the service that uses them can be created”.
Actions in the plan
| Symbol | Action | When it happens |
|---|---|---|
+ | create | In the configuration, not in state |
~ | update in-place | Attribute change, and the provider supports in-place modification (such as container restart policy, network labels depending on the implementation) |
-/+ | replace (delete then create by default) | A ForceNew attribute was changed (port, image, environment variable,upload…), or used -replace |
+/- | replace (create then destroy) | Same as above, but with create_before_destroy = true |
- | destroy | the block removed from the configuration, or terraform destroy |
<= | read (data source) | Data source arguments are unknown at plan time, so the read is deferred until apply |
Why: why lifecycle matters
Most attributes of a Docker container (image, environment variables, ports, mounts) cannot be modified in place, so the provider marks them ForceNew —changing one environment variable means deleting the container and creating a new one. The same applies in the cloud: changing certain VM attributes, a database's storage type, or a subnet CIDR can all trigger replacement, causing downtime or data loss. lifecycle lets you control this.
How: the lifecycle meta-argument
| Argument | Effect | Typical use | Note |
|---|---|---|---|
create_before_destroy = true | Create the new object first, then delete the old one during replacement | Reduce downtime (instances behind a load balancer, certificates) | The old and new objects will coexist: unique attributes such as the name must differ (a fixed name container name will conflict); this setting also propagates to the resources that depend on it |
prevent_destroy = true | Any plan that would delete the resource fails with an error | Data volumes, databases, state storage buckets | Variables cannot be used; removing the entire resource block also removes the protection |
ignore_changes = [attr, …] or all | Ignore changes to these attributes when computing the diff | Attributes modified by external systems (replica counts managed by autoscaling, labels added externally, images deployed by CI) | Only affects the update decision; the configured value is still used at creation |
replace_triggered_by = [ref, …] | When a referenced resource (or one of its attributes) changes or is replaced, this resource is also replaced | Downstream resources that must be rebuilt after the upstream is replaced (nginx caches backend container IPs) | Can only reference managed resources, their instances, or attributes (since 1.4 you can use terraform_data to reference plain values) |
precondition / postcondition | Checks conditions at plan/apply time and errors if they fail | Assumption checks (port > 1024, the image must have a digest) | Introduced in 1.2; covered in depth in Lesson 2 |
Forced replacement and multiple instances
terraform apply -replace="docker_container.app[0]": even if the configuration has not changed, plan this instance for replacement. Suited for “the container state is abnormal and I want to rebuild it”.terraform taintDeprecated.count = 2: createdocker_container.app[0],app[1], and inside a block usecount.index; with map or set keys,for_eachis more stable (Lesson 2) when intermediate elements are added or removed.- Parallelism: graph traversal runs up to 10 operations in parallel by default (
-parallelism=N). Lower it when you hit API rate limits.
When: selection guide
- First try to use references to express dependencies (for example, referencing
docker_container.redis.nameas REDIS_HOST gives you the dependency automatically); only writedepends_onwhen a reference truly isn't possible. - Stateful data (volumes, databases, storage accounts) should always get
prevent_destroy, together with backups. ignore_changesis “acknowledging that others also manage it”; state who and why in a comment.
Comparison with similar technologies
| Terraform | Docker Compose | Kubernetes | CloudFormation | |
|---|---|---|---|---|
| Dependencies | Reference (implicit) + depends_on | depends_on (can carry condition: service_healthy) | No startup order; relies on probes and retries | Ref/GetAtt + DependsOn |
| Replacement strategy | Delete then create by default; create_before_destroy is optional | Recreate the container | Rolling update (maxSurge) | “Replacement” defaults to create then delete |
| Deletion protection | prevent_destroy | None | Finalizers / external policy | DeletionPolicy: Retain, termination protection |
Replacement strategy: delete then create vs. create then delete
Stack in this lesson: which are implicit dependencies and which need depends_on
Interactive: dependency graph traversal and replacement-order simulator
Select an operation, click “Play” or “Next step”, and watch core execute it in batches (waves) following the dependency graph; operations within each batch run in parallel. The log below shows the corresponding CLI output and Docker API calls.
Commands and arguments
| Command | Purpose | Notes |
|---|---|---|
terraform apply -replace=ADDR | Force replacement of a resource instance | Can be repeated; quote the address when it contains square brackets |
terraform plan -target=ADDR | Plan only a particular resource and its dependencies | For emergencies only; Terraform will warn you; do not use as a daily workflow |
terraform apply -parallelism=N | Adjust parallelism | Default 10 |
terraform state list | List resource addresses in state | Module 7 |
terraform show | Show the current state (or a plan file) | -json |
terraform apply -replace='docker_container.app[0]'
# docker_container.app[0] will be replaced, as requested
-/+ resource "docker_container" "app" {
~ id = "a41f…" -> (known after apply)
name = "myapp-dev-app-0"
# (… unchanged attributes hidden)
}
# docker_container.nginx will be replaced due to changes in replace_triggered_by
-/+ resource "docker_container" "nginx" {
~ id = "c9e2…" -> (known after apply)
name = "myapp-dev-nginx"
}
Plan: 2 to add, 0 to change, 2 to destroy.
How to verify: After apply, in docker ps --format '{{.Names}} {{.ID}} {{.RunningFor}}' the creation times of app-0 and nginx are the latest, and app-1 is unchanged. Common errors: Writing app[0] without quotes in bash may be treated by the shell as a wildcard. Production use: Rebuild a VM or container whose state is broken, without modifying the configuration.
Check whether changing an attribute would cause replacement
terraform plan -no-color | grep -E "forces replacement|must be replaced|will be updated in-place"
# docker_container.app[0] must be replaced
~ env = [ # forces replacement
# docker_container.app[1] must be replaced
Lab 4: nginx + myapp + redis full stack, dependencies and lifecycle (about 8 minutes)
cd ~/tf-lab/myapp-stack
cat > app.tf <<'EOF'
# read the image that already exists locally (myapp:1.0 built in Module 0); does not pull from a registry
data "docker_image" "myapp" {
name = "myapp:1.0"
}
resource "docker_container" "app" {
count = 2
name = "${local.name_prefix}-app-${count.index}"
image = data.docker_image.myapp.id
restart = "unless-stopped"
env = ["REDIS_HOST=redis"]
networks_advanced {
name = docker_network.app.id
aliases = ["app"]
}
healthcheck {
test = ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz')"]
interval = "10s"
timeout = "3s"
retries = 3
}
# the configuration contains only the string "redis", so Terraform cannot see the dependency and it must be declared explicitly
depends_on = [docker_container.redis]
}
EOFcat > nginx.tf <<'EOF'
resource "docker_image" "nginx" {
name = "nginx:alpine"
keep_locally = true
}
resource "docker_container" "nginx" {
name = "${local.name_prefix}-nginx"
image = docker_image.nginx.image_id
restart = "unless-stopped"
ports {
internal = 80
external = 8080
}
networks_advanced {
name = docker_network.app.id
}
upload {
file = "/etc/nginx/conf.d/default.conf"
content = <<-EOT
upstream myapp {
%{~ for c in docker_container.app }
server ${c.name}:5000;
%{~ endfor }
}
server {
listen 80;
location = /nginx-health { return 200 "ok\n"; }
location / { proxy_pass http://myapp; }
}
EOT
}
lifecycle {
# nginx resolves backend names at startup and caches the IPs; when a backend container is replaced its IP changes, so nginx is replaced too
replace_triggered_by = [docker_container.app]
}
}
EOFnetwork.tf, and in docker_volume.redis_data add:
resource "docker_volume" "redis_data" {
name = "${local.name_prefix}-redis-data"
lifecycle {
prevent_destroy = true
}
}terraform fmt && terraform validate terraform plan -out=tfplan terraform apply tfplan
data.docker_image.myapp: Reading... data.docker_image.myapp: Read complete after 0s [id=sha256:3f1c2a…] … Plan: 4 to add, 0 to change, 0 to destroy. … docker_image.nginx: Creating... docker_container.app[1]: Creating... docker_container.app[0]: Creating... docker_image.nginx: Creation complete after 3s [id=sha256:9a1b…nginx:alpine] docker_container.app[0]: Creation complete after 1s [id=a41f…] docker_container.app[1]: Creation complete after 1s [id=b72c…] docker_container.nginx: Creating... docker_container.nginx: Creation complete after 1s [id=c9e2…] Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
for i in 1 2 3 4; do curl -s localhost:8080; done
docker exec myapp-dev-nginx cat /etc/nginx/conf.d/default.conf
docker ps --format 'table {{.Names}}\t{{.Status}}'
Hello from a41f0c2d9e11, hits=1
Hello from b72c8e5f4a90, hits=2
Hello from a41f0c2d9e11, hits=3
Hello from b72c8e5f4a90, hits=4
upstream myapp {
server myapp-dev-app-0:5000;
server myapp-dev-app-1:5000;
}
…
NAMES STATUS
myapp-dev-nginx Up 20 seconds
myapp-dev-app-1 Up 22 seconds (healthy)
myapp-dev-app-0 Up 22 seconds (healthy)
myapp-dev-redis Up 5 minutesterraform apply -replace='docker_container.app[0]' -auto-approve for i in 1 2; do curl -s localhost:8080; done # still works (nginx is also rebuilt and gets the new IPs)
Remove replace_triggered_by and try again; you may see nginx return 502, or requests only reach app-1 (nginx still points to the old IP). Add it back when you're done.
terraform plan -destroy
│ Error: Instance cannot be destroyed
│
│ on network.tf line 11:
│ 11: resource "docker_volume" "redis_data" {
│
│ Resource docker_volume.redis_data has lifecycle.prevent_destroy set, but
│ the plan calls for this resource to be destroyed. To avoid this error and
│ continue with the plan, either disable lifecycle.prevent_destroy or reduce
│ the scope of the plan using the -target option.
Keep this setting. The cleanup steps at the end of the course explain how to remove the protection before destroying.
docker_container.app to lifecycle { create_before_destroy = true }, run terraform apply -replace='docker_container.app[0]', observe the Conflict error; then change name to "${local.name_prefix}-app-${count.index}-${substr(uuid(), 0, 4)}" Think about why this is also bad (it changes on every plan, so it is always replaced). The correct approach is to use a random_id resource + keepers (Lesson 2). After the exercise, delete create_before_destroy, and run terraform apply to return to a clean state.Case 1: one label changed and the database was rebuilt
Problem: An engineer changed an apparently harmless attribute on a database instance; nobody looked carefully at the plan in the PR; after apply, the database was deleted and recreated, and data was lost (it could only be restored from backup). Approach: Add prevent_destroy to all stateful resources; CI parses terraform show -json tfplan and when actions includes a resource containing delete it requires extra approval (Lesson 5 implements this with Terraform Policy). Limitations: prevent_destroy does not protect against deleting the whole block; reviewers must watch for deleted blocks.
Case 2: externally modified attributes causing endless diffs
Problem: In the cloud, an autoscaling group's capacity is changed by scaling policies, and every plan wants to set it back to the configured value; Kubernetes node labels on a node pool were added by the cluster. Approach:lifecycle { ignore_changes = [desired_capacity] }, and explain the reason in a comment. Limitations: Ignored attributes can no longer be updated by changing the configuration (you must first remove ignore_changes).
Case 3: zero-downtime certificate replacement
Problem: A certificate referenced by a load balancer is expiring and must be replaced; with the default delete-then-create, deleting the old certificate fails because it is still in use. Approach: The certificate resource uses create_before_destroy = true, and the name uses name_prefix (the cloud service generates a unique suffix); create the new certificate → switch the listener → delete the old certificate. Limitations: create_before_destroy propagates to resources along the dependency chain, so the entire chain must be able to coexist.
Common errors and fixes
Error: Cycle: docker_container.nginx, docker_container.app
Cause: Two resources reference each other (for example, app's env references nginx's name while nginx's template references app), or depends_on and references form a cycle.
terraform graph -type=plan | grep -E '"docker_container\.(app|nginx)'
Fix: Move the shared value into locals (for example, build the name directly from local.name_prefix instead of referencing a resource attribute); remove unnecessary depends_on.
Error: Instance cannot be destroyed — Resource docker_volume.redis_data has lifecycle.prevent_destroy set
Cause: The plan includes deleting a protected resource (a destroy, a changed ForceNew attribute, or other cases besides removing the block from the configuration).
Fix: First confirm that the deletion is really intended and that a backup exists; then change prevent_destroy to false or remove it, and submit that change in a separate PR.
Error: Unable to create container: Error response from daemon: Conflict. The container name "/myapp-dev-app-0" is already in use
Cause:① create_before_destroy ① create_before_destroy conflicts with a fixed name; ② someone manually created a container with the same name; ③ the previous apply was interrupted after the container was created but before it was written to state.
docker ps -a --filter name=myapp-dev-app-0 --format '{{.ID}} {{.Status}} {{.Labels}}'
terraform state list | grep app
Fix:① remove CBD or make the name unique; ②③ after confirming, delete the extra container, or bring it under management with an import block (Lesson 2).
nginx: [emerg] host not found in upstream "myapp-dev-app-0:5000" (the container keeps restarting)
Cause: nginx started when the backend container did not exist or was not on the same network. Usually this is because the template's reference to docker_container.app was removed (losing the dependency), or the network configuration is wrong.
docker logs myapp-dev-nginx --tail 5
docker network inspect myapp-dev-net --format '{{range .Containers}}{{.Name}} {{end}}'
Fix: Make nginx depend on app through a reference (this lab's template already does this), for c in docker_container.app and make sure both are on the same network.
Warning: Resource targeting is in effect / an unexpectedly large number of replacements in the plan
Cause: A -target was used; some dependencies were not planned, so the later full plan shows “make-up” changes; or a value referenced by many resources was changed (a network ID change causes all containers to be replaced).
Fix:-target is for emergencies only; run a full plan/apply right afterward; before changing an underlying resource, look closely at the scope of “forces replacement” in the plan.
1. Rebuild only docker_container.app[1], without changing the configuration.
terraform apply -replace='docker_container.app[1]'
2. List the resource addresses that will be deleted in the plan (including deletions that are part of a replacement).
terraform plan -out=tfplan >/dev/null
terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions | index("delete")) | .address'You change app's env from REDIS_HOST=redis to a reference to "REDIS_HOST=${docker_container.redis.name}". What are the benefits? Is depends_on still needed? What is the effect on the plan?
Benefits: the dependency is expressed automatically through the reference, so depends_on can be removed; and when the Redis container is renamed, app follows automatically. Since the container name is known at plan time (from the configuration), env will not show unknown values. Note that env is ForceNew: when Redis is renamed, app is also replaced (this is the desired behavior, but confirm it in the plan). In addition, to access Redis by container name instead of a network alias, Redis must be in the same user-defined network as app.
Verified teaching videos
No short, verified video dedicated to lifecycle was found.
Official documentation
Video storyboard (about 90 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: in the code,
docker_network.app.id is highlighted, and an arrow runs from the network to the container; another string "redis" has no arrow, and a dashed depends_on line is added beside it.Narration: references create implicit dependencies; Terraform cannot see string conventions, so depends_on must declare them explicitly.
Scene: the container icon first turns red and disappears, then a green new container appears, with the word “downtime” in between; then it switches to a version where the green appears first and the red is removed afterward; when two containers have the same name, a Conflict pops up.
Narration: the default replacement is delete first, then create, which causes downtime; create before destroy creates first and deletes later, but the old and new objects must be able to coexist.
Scene: a lock appears on the data volume, and a red error blocks the destroy command; nginx is replaced along with app.
Narration: prevent_destroy protects stateful resources; replace_triggered_by makes downstream resources follow upstream replacements.
Module 5 · Variables, Outputs, Locals
- Declare accurate type constraints (including
objectandoptional()), defaults,validation,sensitive,nullable. - Remember the precedence of variable assignment: default values <
TF_VAR_environment variables <terraform.tfvars<terraform.tfvars.json<*.auto.tfvars< command line-var/-var-file(in order of appearance; later values override earlier ones). - Understand the real effect of
sensitive: it only hides the value in CLI output,but state still holds it in plaintext. - Use
outputto expose results, uselocalsto eliminate repetition, and know the boundaries of all three.
What: the roles of the three kinds of “values”
| variable (input variable) | locals (local values) | output (output values) | |
|---|---|---|---|
| Analogy | Function parameters | Local variables inside a function | Function return values |
| Who assigns | The caller (CLI, tfvars, environment variables, parent module) | The module author; expressions are evaluated | The module author |
| Can use expressions? | Defaults must be literals (cannot reference other values) | Can reference any value | Can reference any value |
| Referenced by | var.NAME | local.NAME | the parent module's module.M.NAME; the CLI terraform output NAME |
| Written to state? | No (only values used by resources) | No | Yes (root module outputs are stored in state) |
Why: why parameterize
The same configuration must use different replica counts and ports in dev and prod; the same module must be reused by multiple teams; sensitive values (passwords, tokens) must not be hard-coded into Git. Variables extract “things that change”, outputs expose “things others need”, and locals let you write a naming rule only once.
How: the complete form of a variable declaration
variable "app_replicas" {
description = "Number of myapp containers"
type = number
default = 2
nullable = false # error if null is passed in (instead of using null)
validation {
condition = var.app_replicas >= 1 && var.app_replicas <= 5
error_message = "app_replicas must be between 1 and 5."
}
}
variable "app_settings" {
type = object({
log_level = optional(string, "info") # 1.3+: optional attribute with a default
features = optional(list(string), [])
})
default = {}
}
variable "registry_token" {
type = string
sensitive = true # shown as (sensitive value) in CLI output
default = null
}
| Type | Example | Notes |
|---|---|---|
string / number / bool | "dev" / 8080 / true | Primitive types, automatically converted when necessary ("8080" → 8080) |
list(T) / set(T) | ["a","b"] | list is ordered and allows duplicates; set is unordered and deduplicated (commonly used with for_each) |
map(T) | { env = "dev" } | All values have the same type |
object({…}) | { name = "x", port = 80 } | Attribute types may differ; extra attributes are discarded |
tuple([…]) | ["x", 80] | Fixed length, with a fixed type at each position |
any | — | Inferred from the values passed in; use sparingly |
Assignment methods and precedence (from low to high)
- In the variable declaration's
default - Environment variables
TF_VAR_name(for example,export TF_VAR_http_port=8081) terraform.tfvars(loaded automatically)terraform.tfvars.json(loaded automatically)*.auto.tfvars/*.auto.tfvars.json(loaded automatically, in filename alphabetical order)- Command line
-var 'name=value'and-var-file=FILE, processed in the order they appear on the command line; later ones override earlier ones
If a variable has no value and no default, interactive runs prompt for input; in CI, adding -input=false fails immediately, to avoid hanging the pipeline.
The real meaning of sensitive
- Variables and outputs marked sensitive appear as
(sensitive value)in plan/apply output; values derived from them are also treated as sensitive (sensitivity propagates). - It does not encrypt state: passwords in resource arguments are still stored in plaintext in state (Module 7).
terraform output -raw NAMEor-jsoncan read sensitive outputs. - Stronger approach: ephemeral variables/resources (1.10+) and write-only arguments (1.11+) can let values be kept completely out of plan and state; this requires provider support and is covered in Lessons 2 and 3.
When: design recommendations
- Give every variable a
descriptionand a precisetype; where validation is possible, add avalidationto stop errors before the plan. - Only make something a variable if the caller truly needs to decide it; put derived values (name prefixes, tags) in locals.
- Inject sensitive values through environment variables
TF_VAR_or CI secrets, rather than writing them into a tfvars file committed to Git. - Use different tfvars for different environments and separate state (a directory or workspace, Lesson 2); otherwise switching tfvars would change dev resources into prod.
Comparison with similar technologies
| Terraform | Bicep | Ansible | Helm | |
|---|---|---|---|---|
| Input | variable + tfvars | param + .bicepparam | inventory vars / extra-vars (22 levels of precedence) | values.yaml + --set |
| Validation | type + validation | decorators @minValue, @allowed | argument_spec / assert | values.schema.json |
| Sensitive | sensitive (still plaintext in state), ephemeral | @secure() | Vault / no_log | No built-in |
-var/-var-file has higher precedence,*.auto.tfvars also ranks above it. ④ “TF_VAR_ environment variables override tfvars”—the opposite: tfvars override environment variables.Where variable values come from: the precedence ladder
Data flow: variable → locals → resource → output
Interactive: variable precedence calculator
Check the boxes for var.http_port the sources of values (you can change each source's value), then click “Calculate”. The simulator applies them layer by layer in Terraform's loading order, shows which sources core actually sees and the final value, and also demonstrates type conversion and validation.
Commands and arguments
| Command / argument | Purpose | Notes |
|---|---|---|
-var 'name=value' | Assign on the command line | For complex types, use HCL syntax: -var 'tags={a="1"}' |
-var-file=prod.tfvars | Load an extra variable file | Can be repeated; later files override earlier ones |
-input=false | Disable interactive prompts | Required in CI |
TF_VAR_name | Assign via environment variables | Suitable for injecting secrets |
terraform output [NAME] | Read outputs | -json,-raw (a single string or number, convenient for scripts) |
terraform plan -var 'app_replicas=3' # temporary override TF_VAR_http_port=8081 terraform plan # environment variable terraform plan -var-file=prod.tfvars -input=false # specify a file, disable prompts terraform output -json | jq . curl -s "$(terraform output -raw url)"
{
"app_containers": {
"sensitive": false,
"type": ["tuple", ["string", "string"]],
"value": ["myapp-dev-app-0", "myapp-dev-app-1"]
},
"app_secret": {
"sensitive": true,
"type": "string",
"value": "kq3Z… (plaintext!)"
},
"url": { "sensitive": false, "type": "string", "value": "http://localhost:8080" }
}
Hello from a41f0c2d9e11, hits=5
How to verify:terraform output (no arguments), sensitive outputs show as <sensitive>, whereas -json gives plaintext, so do not print output -json in CI logs. Common errors: In Windows PowerShell the quoting rules differ; -var for complex values, use a tfvars file instead. Production use: Later pipeline steps use terraform output -raw to get the URL and ID for smoke tests.
Lab 5: parameterize the myapp stack, experience precedence and sensitive (about 7 minutes)
cd ~/tf-lab/myapp-stack
cat > variables.tf <<'EOF'
variable "project" {
description = "Project name, the prefix for all Docker object names"
type = string
default = "myapp"
}
variable "env" {
description = "Environment name"
type = string
default = "dev"
validation {
condition = contains(["dev", "prod"], var.env)
error_message = "env must be dev or prod."
}
}
variable "app_image" {
description = "myapp image (must already exist locally)"
type = string
default = "myapp:1.0"
}
variable "app_replicas" {
description = "Number of myapp containers"
type = number
default = 2
nullable = false
validation {
condition = var.app_replicas >= 1 && var.app_replicas <= 5
error_message = "app_replicas must be between 1 and 5."
}
}
variable "http_port" {
description = "Port published on the host by nginx"
type = number
default = 8080
validation {
condition = var.http_port > 1024 && var.http_port < 65536
error_message = "Please use an unprivileged port between 1025 and 65535."
}
}
EOF# app.tf: count, image, environment variables
sed -i 's/ count = 2/ count = var.app_replicas/; s/ name = "myapp:1.0"/ name = var.app_image/' app.tf
sed -i 's/ env = \["REDIS_HOST=redis"\]/ env = ["REDIS_HOST=redis", "APP_SECRET=${random_password.app.result}"]/' app.tf
# nginx.tf: port
sed -i 's/ external = 8080/ external = var.http_port/' nginx.tf
cat > secrets.tf <<'EOF'
resource "random_password" "app" {
length = 24
special = false
}
EOF
cat > outputs.tf <<'EOF'
output "network_name" {
description = "Application network name"
value = docker_network.app.name
}
output "redis_container" {
value = docker_container.redis.name
}
output "url" {
description = "Access entry point"
value = "http://localhost:${var.http_port}"
}
output "app_containers" {
value = docker_container.app[*].name
}
output "app_secret" {
value = random_password.app.result
sensitive = true
}
EOF
grep -nE 'count|name *= var|APP_SECRET|external' app.tf nginx.tf
terraform init -upgrade >/dev/null && terraform validate
The sed command relies on the original form from Module 4; if it does not match, edit the corresponding line manually. random The provider was declared in Module 2 and is used here for the first time, so re-run init (if it is already in the lock file, this just installs it).
terraform plan
# random_password.app will be created
+ resource "random_password" "app" {
+ result = (sensitive value)
…
# docker_container.app[0] must be replaced
-/+ resource "docker_container" "app" {
~ env = (sensitive value) # forces replacement
…
Plan: 4 to add, 0 to change, 3 to destroy.
Changes to Outputs:
+ app_containers = [ "myapp-dev-app-0", "myapp-dev-app-1" ]
+ app_secret = (sensitive value)
+ url = "http://localhost:8080"
env references a sensitive value, so the entire env list is shown as (sensitive value)— this is sensitivity propagation. Changing env is ForceNew, so app is replaced, and nginx follows the replacement via replace_triggered_by. Run terraform apply.
cat > terraform.tfvars <<'EOF' app_replicas = 2 http_port = 8080 EOF export TF_VAR_http_port=9090 terraform plan -input=false | grep -E 'external|No changes' # tfvars (8080) overrides the environment variable (9090) terraform plan -var 'http_port=8088' | grep -E 'external' # command line is highest: 8080 -> 8088 unset TF_VAR_http_port
No changes. Your infrastructure matches the configuration.
~ external = 8080 -> 8088 # forces replacementterraform plan -var 'app_replicas=9'
│ Error: Invalid value for variable
│
│ on variables.tf line 25:
│ 25: variable "app_replicas" {
│ ├────────────────
│ │ var.app_replicas is 9
│
│ app_replicas must be between 1 and 5.cat > prod.tfvars <<'EOF' env = "prod" app_replicas = 3 http_port = 8090 EOF terraform plan -var-file=prod.tfvars 2>&1 | grep -E "must be replaced|Error:" | head
│ Error: Instance cannot be destroyed …(without prevent_destroy, you would see:) # docker_container.app[0] must be replaced # docker_container.nginx must be replaced # docker_container.redis must be replaced # docker_network.app must be replaced # docker_volume.redis_data must be replaced
Switching env within the same state would turn all dev resources replaced with prod resources (the name prefix changed, and name is ForceNew) — the volume's replacement is prevent_destroy blocked, so the whole plan fails. This shows exactly why multiple environments need separate state (Lesson 2), rather than switching tfvars against the same state.
terraform output # app_secret = <sensitive> terraform output -raw app_secret; echo # plaintext grep -c "$(terraform output -raw app_secret)" terraform.tfstate # appears multiple times in state
app_containers = [ "myapp-dev-app-0", "myapp-dev-app-1", ] app_secret = <sensitive> … kq3Zr8… 3
Case 1: injecting secrets in CI
Problem: The database administrator password was written in prod.tfvars and committed to Git. Approach: Remove it from tfvars and inject it in GitHub Actions as a secret TF_VAR_db_admin_password ; set the variable sensitive = true; as a further step, have Terraform generate a random password and write it to Key Vault, or use a write-only argument (Lesson 3). Rotate the leaked password and clean up the Git history. Limitations: As long as the password is a normal resource argument, it will exist in state.
Case 2: using validation to prevent costly typos
Problem: Someone wrote a 96-core VM size in tfvars. Approach:validation { condition = contains(local.allowed_sizes, var.vm_size) }— note that since 1.9, validation can reference other variables and locals; before that it could only reference itself. Limitations: validation only applies within this module; for organization-wide rules, use Terraform Policy / Sentinel / OPA (Lesson 5).
Case 3: outputs for downstream pipelines
Problem: The deployment pipeline needs the load balancer address created by Terraform for smoke testing. Approach: Define output "url", and the pipeline runs curl -fsS "$(terraform output -raw url)/healthz". For sharing across states, use a terraform_remote_state data source or (more recommended) write to parameter storage / service discovery (Lesson 2). Limitations: Output values are stored in state, so anyone with permission to read state can see them.
Common errors and fixes
Error: Invalid value for variable — app_replicas must be between 1 and 5.
Cause: The validation condition evaluated to false.
Fix: Correct the input; if the rule is too strict, change the validation (in a separate PR).
Error: No value for required variable — The root module input variable "db_password" is not set, and has no default value.
Cause: The variable has no default, and -input=false (CI) provides no value.
env | grep ^TF_VAR_; ls *.tfvars *.auto.tfvars 2>/dev/null
Fix: Provide it via tfvars,-var or TF_VAR_db_password . Note that environment variable names are case-sensitive and must exactly match the variable name.
Error: Invalid value for input variable — a number is required (for example, -var 'http_port=abc')
Cause: The value cannot be converted to the declared type.
Fix: Check the type; for complex types on the command line, use HCL syntax with correct quoting; a tfvars file is recommended.
Error: Output refers to sensitive values — To reduce the risk of accidentally exporting sensitive data … the output must be marked as sensitive
Cause: An output references a sensitive value but does not declare sensitive = true.
Fix: Add sensitive = true to the output; when you are sure it is not sensitive, you can use nonsensitive() (use with caution).
Warning: Value for undeclared variable — The root module does not declare a variable named "app_replica"
Cause: A variable name in tfvars is misspelled or was removed (an undeclared variable on the command line -var is an error).
Fix: Correct the spelling; delete obsolete entries so you don't assume a setting took effect.
1. Without modifying any files, run a plan with 3 replicas, and make sure CI does not hang on interactive input.
terraform plan -input=false -var 'app_replicas=3'
2. In a script, get the url output and perform a health check.
curl -fsS "$(terraform output -raw url)/nginx-health"
The environment simultaneously has TF_VAR_http_port=9000,terraform.tfvars (http_port = 8080),zz.auto.tfvars (http_port = 8085), and you run terraform plan -var-file=ci.tfvars (http_port = 8099). What is the final value? What if -var-file is removed?
With -var-file the value is 8099 (the command line has the highest precedence). Without it, the value is 8085: *.auto.tfvars ranks above terraform.tfvars, and both rank above the environment variable.
Verified teaching videos
Official documentation
Video storyboard (about 80 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: a function diagram, with the input port labeled variable, the interior labeled locals, and the output port labeled output.
Narration: variables are parameters, locals are internal computations, and outputs are return values.
Scene: five steps light up in turn: default, environment variable, tfvars, auto tfvars, command line; the final value lands on the highest step.
Narration: from lowest to highest precedence: default value, environment variable, tfvars, auto tfvars, command line.
Scene: in the terminal, the password shows as sensitive value; the camera cuts to the state file, where the same password appears in plaintext, circled by a red box.
Narration: sensitive only hides values on screen; state still contains plaintext. Protect the state.
Module 6 · Data Sources and Expression Functions
- Explain the difference between data sources and resources, and the conditions for reading a data source at plan time or deferring the read to apply (
<=) time. - Use common built-in functions fluently: string, collection, encoding, file and template, network, type conversion, and error handling (
try/can). - Write list/map forms of the
forexpressions (includingiffiltering and grouping...), splat[*], conditional expressions, anddynamicblocks. - Use
terraform consoleto interactively debug expressions.
What: data sources
data A data block lets Terraform read external information without managing its lifecycle: an existing network, the latest digest of an image, AMI/image versions in the cloud, the current signed-in identity, a VNet maintained by another team…… The provider implements this through ReadDataSource gRPC calls.
data "docker_registry_image" "nginx" { # query the digest that the tag currently points to in the image registry
name = "nginx:alpine"
}
resource "docker_image" "nginx" {
name = "nginx:alpine"
keep_locally = true
pull_triggers = [data.docker_registry_image.nginx.sha256_digest] # digest changes → re-pull
}
| resource | data | |
|---|---|---|
| Lifecycle | Create / update / delete | Read-only; re-read on every plan |
| state | Records the ID and attributes | Results are also recorded in state (for reference), but there is no “destroy” |
| Address | docker_image.nginx | data.docker_registry_image.nginx |
| Plan symbol | + ~ -/+ - | <= (deferred until read during apply) |
When it is read: If all of a data source's arguments are known at plan time, and it does not depend on resources with pending changes, it is read during the plan phase; if its arguments reference known after apply values, or it sets depends_on and a dependency has changes, it is deferred to apply, and attributes that downstream resources reference from it also become unknown in the plan.
Why: why functions and expressions are needed
Real configurations are full of derived values: generating an upstream list from the replica count, choosing a size based on the environment, expanding a map into multiple nested blocks, rendering config files, calculating subnets…… HCL does not support custom functions, but it provides more than 100 built-in functions, plus provider-supplied functions (1.8+, syntax provider::NAME::FUNC(…)), which are enough to cover the vast majority of needs.
How: categories of common functions
| Category | Functions | Example → result |
|---|---|---|
| Strings | format join split upper lower replace trimspace substr startswith | join(",", ["a","b"]) → "a,b" |
| Collections | length concat merge flatten distinct keys values lookup contains zipmap element slice range | merge({a=1},{b=2}) → {a=1,b=2} |
| Type conversion | tostring tonumber tolist toset tomap | toset(["a","a"]) → ["a"] |
| Encoding | jsonencode jsondecode yamlencode yamldecode base64encode urlencode | jsonencode({a=1}) → "{\"a\":1}" |
| Files and templates | file templatefile fileexists filesha256 fileset | templatefile("x.tftpl", {n=2}) |
| Network | cidrsubnet cidrhost cidrnetmask | cidrsubnet("10.20.0.0/16", 8, 1) → "10.20.1.0/24" |
| Hash / random identifiers | sha256 md5 uuid timestamp | uuid(),timestamp() change on every evaluation; avoid using them for resource arguments |
| Error handling | try can coalesce one | try(var.cfg.port, 80) |
| Sensitivity | sensitive nonsensitive | Manual marking / unmarking |
| Provider functions | Built-in terraform provider: provider::terraform::encode_tfvars,decode_tfvars,encode_expr | the Functions section of each provider's documentation |
Expression structure
locals {
# for in list form: [for element in collection : result if condition]
app_names = [for c in docker_container.app : c.name]
# for in map form: {for element in collection : key => value}
app_ips = { for c in docker_container.app : c.name => c.network_data[0].ip_address }
# filtering and grouping (... collects values with the same key into a list)
by_env = { for s in var.services : s.env => s.name... }
# splat: equivalent to [for c in docker_container.app : c.name]
app_names2 = docker_container.app[*].name
# conditional expression
replicas = var.env == "prod" ? 3 : 1
}
# dynamic block: generate multiple nested blocks from a collection
dynamic "labels" {
for_each = local.common_labels
content {
label = labels.key # the iterator variable name defaults to the block name
value = labels.value
}
}
When: when to use data, and when to use variables
- Values maintained by other systems or teams that change (image digest, shared network ID) → data source, to avoid copy-pasting stale IDs.
- Values that are your decisions (replica count, port) → variables.
- A data source calls the API on every plan: too many queries slow down plans and trigger rate limiting (Docker Hub has rate limits for anonymous pulls).
Comparison with similar technologies
| Terraform | Bicep | CloudFormation | Pulumi | |
|---|---|---|---|---|
| Read existing resources | data block | existing keyword | Arguments + SSM dynamic references / imported values | get* Functions |
| Loop generation | for,dynamic,count/for_each | for Loops | Fn::ForEach (language extension) | Native to the language |
| Templates | templatefile | loadTextContent + string functions | Fn::Sub | Native to the language |
-refresh=false). ② “Adding depends_on to a data source is safer”—it defers the read to apply, causing many “known after apply” values and unnecessary replacements. ③ “templatefile can read variables with var.x”—a template can only use variables from the map passed in. ④ “uuid()/timestamp() are good for generating names”—they change on every plan, so the resource will always show a change; use random_* resources instead.Data source read at plan time vs. deferred to apply
How a for expression is evaluated
Interactive: for expression lab
Select an expression and click “Step through evaluation”. The simulator shows how Terraform iterates over the collection, binds iterator variables, applies if filtering, and assembles the result, matching the result you get in terraform console .
terraform console Related commands
| Command | Purpose | Notes |
|---|---|---|
terraform console | Interactive evaluation (can reference var, local, resources, data) | Reads the current state; exit or press Ctrl+D to exit |
echo 'EXPR' | terraform console | Non-interactive evaluation | Suitable for scripts and quizzes |
terraform console -var 'x=1' | Start with variables | Same variable arguments as plan |
terraform metadata functions -json | List all available functions and their signatures | Requires a newer version; results depend on the local version |
cd ~/tf-lab/myapp-stack terraform console
> local.name_prefix
"myapp-dev"
> upper(var.env)
"DEV"
> cidrsubnet("10.20.0.0/16", 8, 1)
"10.20.1.0/24"
> [for c in docker_container.app : c.name]
[
"myapp-dev-app-0",
"myapp-dev-app-1",
]
> { for c in docker_container.app : c.name => c.network_data[0].ip_address }
{
"myapp-dev-app-0" = "10.20.0.3"
"myapp-dev-app-1" = "10.20.0.4"
}
> try(var.does_not_exist, "fallback")
╷
│ Error: Reference to undeclared input variable
> try(local.common_labels.owner, "unknown")
"unknown"
> jsonencode(local.common_labels)
"{\"env\":\"dev\",\"managed_by\":\"terraform\",\"project\":\"myapp\"}"
> random_password.app.result
(sensitive value)
> nonsensitive(length(random_password.app.result))
24
How to verify: The console reads state, so resource attributes have values only after apply. Common errors:try Can only catch dynamic errors (missing attributes, failed type conversions); referencing an undeclared variable is a static error that try cannot catch. Production use: Before writing complex for/merge expressions, verify them in the console, or use echo | terraform console for assertions in CI.
Lab 6: automatically update the image by digest, and generate the nginx configuration from a template (about 7 minutes)
nginx.tf the image section at the top:
data "docker_registry_image" "nginx" {
name = "nginx:alpine"
}
resource "docker_image" "nginx" {
name = "nginx:alpine"
keep_locally = true
pull_triggers = [data.docker_registry_image.nginx.sha256_digest]
}
terraform plan
data.docker_registry_image.nginx: Reading...
data.docker_registry_image.nginx: Read complete after 1s [id=sha256:4f3c…]
# docker_image.nginx must be replaced
-/+ resource "docker_image" "nginx" {
+ pull_triggers = [ # forces replacement
+ "sha256:4f3c…",
]
…
The first time you add pull_triggers will replace the image resource (re-pull); afterwards it only changes when the upstream tag points to a new digest. This is “automatic discovery of security updates to the image”. In production, it is better to pin the image to a digest (nginx@sha256:…), and let Renovate open PRs to update it. Run terraform apply.
cat > nginx.conf.tftpl <<'EOF'
upstream myapp {
%{ for name in upstreams ~}
server ${name}:5000;
%{ endfor ~}
}
server {
listen 80;
location = /nginx-health { return 200 "ok\n"; }
location / { proxy_pass http://myapp; }
}
EOF
In nginx.tf , replace the upload block's content = <<-EOT … EOT entire section with:
upload {
file = "/etc/nginx/conf.d/default.conf"
content = templatefile("${path.module}/nginx.conf.tftpl", {
upstreams = docker_container.app[*].name
})
}
terraform fmt && terraform plan
If the rendered result matches the previous output byte for byte, it shows No changes; if there are whitespace differences, nginx will be replaced (harmless). In the template, ~ remove the newline after the directive to avoid producing empty lines.
outputs.tf , append at the end:
cat >> outputs.tf <<'EOF'
output "app_ips" {
description = "container name => IP on the application network"
value = { for c in docker_container.app : c.name => c.network_data[0].ip_address }
}
EOF
terraform apply -auto-approve >/dev/null && terraform output app_ips
{
"myapp-dev-app-0" = "10.20.0.3"
"myapp-dev-app-1" = "10.20.0.4"
}terraform apply -var 'app_replicas=3' -auto-approve | tail -2 docker exec myapp-dev-nginx cat /etc/nginx/conf.d/default.conf | head -5 terraform apply -auto-approve | tail -1 # back to the 2 replicas in tfvars
Apply complete! Resources: 2 added, 0 changed, 1 destroyed.
upstream myapp {
server myapp-dev-app-0:5000;
server myapp-dev-app-1:5000;
server myapp-dev-app-2:5000;
}
Apply complete! Resources: 1 added, 0 changed, 2 destroyed.
2 added = app[2] + new nginx; 1 destroyed = old nginx. When scaling in, app[2] and the old nginx are deleted and a new nginx is created.
echo '…' | terraform console to find: ① a comma-joined string of all app container names; ② common_labels the uppercase list of all keys in
echo 'join(",", docker_container.app[*].name)' | terraform console
echo '[for k in keys(local.common_labels) : upper(k)]' | terraform consoleCase 1: reference the shared network instead of copying the ID
Problem: The application team's configuration hard-coded the resource ID of the platform team's VNet; after the platform team rebuilt the network, all of the application team's applies failed. Approach: Switch to data sources that look up by name or tag (Azure data "azurerm_virtual_network", AWS data "aws_vpc" filtered by tag); the platform team commits to a name/tag contract. Limitations: If a data source cannot find its target, it errors immediately (most providers' data sources error when “not found”); this is the desired fast failure.
Case 2: for_each + rules driven by a data file
Problem: 300 firewall rules are maintained in YAML in the repository. Approach:locals { rules = yamldecode(file("${path.module}/rules.yaml")) }, use { for r in local.rules : r.name => r } to convert them into a map for_each; the security team only edits the YAML. Limitations: Map keys must be stable and unique; changing a key causes delete + recreate.
Case 3: AMI/image version drift
Problem: Using most_recent = true image data source caused every VM to be replaced at each new image release in plan. Approach: Pin the image version in a variable, updated by the pipeline during a maintenance window; or set ignore_changes on the VM's image attribute and update through a rolling replacement process. Limitations:“Automatically following the latest” vs. “stable plans” is a trade-off; production environments usually choose the latter.
Common errors and fixes
Error: Invalid for_each argument / The "for_each" value depends on resource attributes that cannot be determined until apply
Cause:for_each/count The keys of this block depend on values known only after apply (such as resource IDs). Terraform must know how many instances exist at plan time.
Fix: Use values known in the configuration (variables, names) as keys; or apply in two steps (first -target create the upstream; for emergencies only).
Error: Unable to read Docker image into resource: unable to find or pull image myapp:1.0 (data "docker_image")
Cause:data "docker_image" It only reads images that already exist locally.
docker image ls myapp
Fix: Go back to Module 0 and build myapp:1.0. (The exact error text may differ slightly depending on the provider version.)
Error: Got error when attempting to fetch image version from registry: … 429 Too Many Requests
Cause:docker_registry_image Every plan accesses Docker Hub, and anonymous requests are rate limited.
Fix: Configure registry_auth in the provider (using an access token passed through an environment variable), or switch to an image cache or private registry; reduce unnecessary plan runs in CI.
Error: Invalid template interpolation value — Cannot include the given value in a string template: string required.
Cause: In ${ } you put a list or map.
Fix: Use join(),jsonencode() or the %{ for } in the template.
Error: Duplicate object key — Two different items produced the key "dev" in this 'for' expression.
Cause: A map-form for expression produced duplicate keys.
Fix: Use a unique key, or add ... for grouping: { for s in var.services : s.env => s.name... }.
1. Without entering interactive mode, compute 10.20.0.0/16 's 3rd /24 subnet (index 2).
echo 'cidrsubnet("10.20.0.0/16", 8, 2)' | terraform console # "10.20.2.0/24"2. Write a for expression that keeps only the container names that start with -app- and whose trailing number is even.
[for i, c in docker_container.app : c.name if i % 2 == 0]
A colleague added data "docker_registry_image" "nginx" to depends_on = [docker_container.app], and every time app is modified, plan shows the nginx image and the nginx container as “known after apply / must be replaced”. Why? How should it be changed?
When the data source's depends_on points to resources with pending changes, the read is deferred to apply, and the digest is unknown in the plan → pull_triggers unknown → the image (ForceNew) is planned for replacement → the image ID is unknown → the nginx container is replaced. Remove depends_on: querying the registry does not depend on app in the first place.
Verified teaching videos
No short, verified video dedicated to for expressions was found.
Official documentation
Video storyboard (about 80 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: Terraform sends a read-only request to the image registry and gets back a sha256 digest; next to it, the resource icon says “create/update/delete”, and the data icon says only “read”.
Narration: a data source is read-only and never writes; it is re-read on every plan.
Scene: two container cards enter the for expression funnel one after another, and the exit produces a map of “name equals IP”.
Narration: a for expression binds elements one at a time; square brackets produce a list, curly braces produce a map, and if is used to filter.
Scene: in the terminal, terraform console takes cidrsubnet as input and outputs the result immediately.
Narration: try complex expressions in the console first, then write them into the configuration.
Module 7 · State Basics
- Explain why Terraform needs state: the mapping, metadata (dependencies, schema version), performance, and the foundation for multi-person collaboration.
- Read
terraform.tfstate's structure:version,serial,lineage,outputs,resources[].instances[]. - Know state's sensitivity (plaintext secrets) and the correct way to protect it; understand why you should not edit state by hand and which commands to use instead.
- Use
state list,state show,show -json, and useplan/apply -refresh-onlyto identify and handle drift.
What: what state is
state is a JSON file (locally by default terraform.tfstate, and stored in a remote backend for teams), recording the world as Terraform knew it after its last operation:
- Mapping:
docker_container.app[0]↔ Docker container IDa41f…. The configuration contains only names, not IDs; without state, Terraform does not know which real object is “its own”. - Attribute cache: all attribute values from the last read or write (including values computed by the provider, such as IP and digest).
- Metadata: for each instance, the dependency list (so that destruction still works in the right order after the configuration is removed), schema version, provider address, and private data.
- outputs: output values of the root module.
{
"version": 4,
"terraform_version": "1.17.2",
"serial": 14,
"lineage": "8f0c7a6e-3b1d-…",
"outputs": {
"url": { "value": "http://localhost:8080", "type": "string" },
"app_secret": { "value": "kq3Zr8…", "type": "string", "sensitive": true }
},
"resources": [
{
"mode": "managed",
"type": "docker_container",
"name": "app",
"provider": "provider[\"registry.terraform.io/kreuzwerker/docker\"]",
"instances": [
{
"index_key": 0,
"schema_version": 2,
"attributes": {
"id": "a41f0c2d9e11…",
"name": "myapp-dev-app-0",
"env": ["APP_SECRET=kq3Zr8…", "REDIS_HOST=redis"],
"network_data": [{ "ip_address": "10.20.0.3", "network_name": "myapp-dev-net" }],
…
},
"sensitive_attributes": [ … ],
"dependencies": ["data.docker_image.myapp", "docker_container.redis", "docker_network.app", "random_password.app"]
}
]
}
],
"check_results": null
}
| Field | Meaning |
|---|---|
version | State file format version (currently 4) |
serial | Incremented each time the state content changes; remote backends use it to prevent an old state from overwriting a new one |
lineage | A UUID generated when the state is first created; states with different lineages cannot overwrite each other (prevents pushing dev state to prod) |
mode | managed (resource) or data (data source) |
index_key | The numeric index for count or the string key for for_each |
sensitive_attributes | Which attribute paths are sensitive (used for CLI display),but the values themselves are still plaintext |
Why: why you cannot “query the real world directly”
- Many APIs cannot determine in reverse whether “this object was created by this configuration” (names can be duplicated and can be changed).
- After a configuration block is deleted, Terraform needs to know from state that “it once existed and what its ID was” in order to delete it.
- In large environments, querying every object one by one is slow; state lets Terraform read precisely by ID (and you can use
-refresh=falseor, in 1.17,-minimal-refreshto reduce reads further).
How: refresh and drift
Every plan/apply first runs refresh: it calls ReadResource for each resource in state to get the real attributes. If the real value differs from state, that is drift. The CLI prints “Note: Objects have changed outside of Terraform”. Then it compares the refreshed state with the configuration to generate the plan.
| Command | What it does | Writes state? | Changes the real world? |
|---|---|---|---|
terraform plan | refresh (in memory) + compute diff | No | No |
terraform plan -refresh-only | Only shows drift | No | No |
terraform apply -refresh-only | Writes drift into state (“accept reality”) | Yes | No |
terraform apply | Converges the real world to the configuration (“fix drift”) | Yes | Yes |
terraform refresh | Deprecated, equivalent to apply -refresh-only -auto-approve (no confirmation, dangerous) | Yes | No |
plan -refresh=false | Skips refresh and computes from state directly (fast, but may be based on stale information) | No | No |
plan -minimal-refresh (1.17) | Only refreshes resources with proposed changes | No | No |
State sensitivity
- Passwords, private keys, connection strings, random_password results, and sensitive outputs in resource attributes are all stored in state as plaintext.
- Protective measures: do not commit to Git (
.gitignore); teams use a remote backend (S3 / Azure Storage / HCP Terraform) with server-side encryption, least privilege, versioning, and access auditing (Lesson 2); where possible, use ephemeral/write-only to keep secrets out of state. OpenTofu additionally offers client-side state encryption.
Why not to edit state by hand
- State contains serial, lineage, schema_version, private data, and dependency relationships; manual edits easily break consistency and can cause Terraform to delete or duplicate resources.
- The right tools:
terraform state mv(or amovedblock, to change the address),terraform state rm(or aremovedblock, to stop managing without deleting the object),importblock (to bring under management),-replace(to rebuild),state pull/push(backup and restore; push validates serial/lineage). These are practiced in detail in Lesson 2.
When: when you need to care about state
- Two or more people collaborating, or CI involved → remote backend + locking (Lesson 2).
- Refactoring (renaming, moving into a module) → use moved blocks instead of deleting and recreating.
- Drift discovered → first decide “who is right”: if the configuration is right, apply to fix it; if reality is right, change the configuration (refresh-only first if necessary).
Comparison with similar technologies
| Terraform | CloudFormation | Bicep / ARM | Pulumi | Ansible | |
|---|---|---|---|---|---|
| State storage | tfstate (you manage storage) | AWS-managed stack | None (deployment history; Deployment Stacks track managed resources) | Pulumi Cloud / self-managed backend | None |
| Drift detection | plan / plan -refresh-only | Drift detection (console/API) | what-if | pulumi refresh / preview | --check --diff |
| Secrets | State in plaintext (must be protected) | AWS-managed | @secure not recorded | Encrypts secrets by default | Vault |
Three-way comparison: configuration · state · real world
When state is written, and backups
Interactive: configuration · state · real world — create and handle drift
First click the “Create change” button above (simulating someone manually operating Docker or changing the configuration), then click the Terraform command below. Observe how the three columns change, who writes state, and whether the serial increments.
State inspection commands
| Command | Purpose | Notes |
|---|---|---|
terraform state list | List all resource addresses | Can be filtered: terraform state list 'docker_container.app',-id=ID |
terraform state show ADDR | Show the attributes of a single resource in HCL style | Sensitive values are displayed as (sensitive value) |
terraform show | Show the entire state (or a plan file) | -json Output in a machine-readable format (includes plaintext sensitive values) |
terraform state pull | Output the raw state JSON (also works with remote backends) | Backup: terraform state pull > backup.tfstate |
terraform plan -refresh-only | View drift only | Scheduled drift detection in CI |
terraform apply -refresh-only | Accept drift and write it to state | Requires confirmation |
terraform state mv / rm,import | Controlled ways to modify state | Lesson 2 |
cd ~/tf-lab/myapp-stack terraform state list terraform state show 'docker_container.app[0]' | head -20
data.docker_image.myapp
data.docker_registry_image.nginx
docker_container.app[0]
docker_container.app[1]
docker_container.nginx
docker_container.redis
docker_image.nginx
docker_image.redis
docker_network.app
docker_volume.redis_data
random_password.app
# docker_container.app[0]:
resource "docker_container" "app" {
attach = false
command = [
"gunicorn",
"-b",
"0.0.0.0:5000",
"app:app",
]
env = (sensitive value)
hostname = "a41f0c2d9e11"
id = "a41f0c2d9e11…"
image = "sha256:3f1c2a…"
name = "myapp-dev-app-0"
restart = "unless-stopped"
…
Read state with jq (read-only!)
jq '{version, terraform_version, serial, lineage}' terraform.tfstate
jq -r '.resources[] | "\(.mode) \(.type).\(.name) instances=\(.instances|length)"' terraform.tfstate
terraform show -json | jq -r '.values.root_module.resources[] | select(.type=="docker_container") | "\(.address) \(.values.network_data[0].ip_address)"'
{
"version": 4,
"terraform_version": "1.17.2",
"serial": 14,
"lineage": "8f0c7a6e-3b1d-4c55-9a0e-1f2b3c4d5e6f"
}
data docker_image.myapp instances=1
data docker_registry_image.nginx instances=1
managed docker_container.app instances=2
…
docker_container.app[0] 10.20.0.3
docker_container.app[1] 10.20.0.4
docker_container.nginx 10.20.0.6
docker_container.redis 10.20.0.2
How to verify: After every apply that makes changes, serial increments and lineage stays the same. Common errors: Reading terraform.tfstate directly only works with a local backend; for remote backends use terraform state pull or terraform show -json. Production use: Audit “which configuration manages this container/VM” (state list -id=…), and export inventories for the CMDB.
Lab 7: read the state, create and handle drift (about 8 minutes)
cd ~/tf-lab/myapp-stack terraform plan -detailed-exitcode >/dev/null; echo "exit=$?" # 0 = no changes jq .serial terraform.tfstate cp terraform.tfstate /tmp/tfstate.before
exit=0 14
terraform state show random_password.app | grep result jq -r '.resources[] | select(.type=="random_password") | .instances[0].attributes.result' terraform.tfstate
result = (sensitive value) kq3Zr8… (plaintext)
Anyone who can read the state file can see it. This is why state must be kept in controlled storage and must not be committed to Git.
docker rm -f myapp-dev-app-1 # delete a managed container docker update --restart=no myapp-dev-redis # change an attribute of a managed container docker run -d --name debug --network myapp-dev-net busybox sleep 3600 # manually create an unmanaged container
terraform plan -refresh-only
Note: Objects have changed outside of Terraform
Terraform detected the following changes made outside of Terraform since the
last "terraform apply" which may have affected this plan:
# docker_container.app[1] has been deleted
- resource "docker_container" "app" {
- id = "b72c8e5f4a90…" -> null
- name = "myapp-dev-app-1" -> null
# (… unchanged attributes hidden)
}
# docker_container.redis has changed
~ resource "docker_container" "redis" {
id = "9d4a2e…"
name = "myapp-dev-redis"
~ restart = "unless-stopped" -> "no"
# (… unchanged attributes hidden)
}
This is a refresh-only plan, so Terraform will not take any actions to undo
these. If you were expecting these changes then you can apply this plan to
record the updated values in the Terraform state without changing any remote
objects.
debug The container does not appear at all — it is not in state.
terraform plan -detailed-exitcode; echo "exit=$?"
# docker_container.app[1] will be created
+ resource "docker_container" "app" { … name = "myapp-dev-app-1" … }
# docker_container.nginx will be replaced due to changes in replace_triggered_by
…
# docker_container.redis will be updated in-place
~ resource "docker_container" "redis" {
~ restart = "no" -> "unless-stopped"
}
Plan: 2 to add, 1 to change, 1 to destroy.
exit=2
restart It can be modified in place through Docker's container update API, so it is ~; the deleted app[1] needs to be rebuilt; nginx follows the replacement via replace_triggered_by. Exit code 2 means “there are changes”.
terraform apply -refresh-only -auto-approve | tail -2 jq .serial terraform.tfstate terraform plan | grep -E "restart|will be created|Plan:"
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
15
~ restart = "no" -> "unless-stopped"
# docker_container.app[1] will be created
Plan: 2 to add, 1 to change, 1 to destroy.
refresh-only wrote the drift into state (serial 15, app[1] disappeared from state, restart recorded as no), but the configuration did not change, so the next plan still changes reality back to the configuration. To truly “accept” a drift, you must change the configuration as well.
terraform apply -auto-approve | tail -1
docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' myapp-dev-redis
curl -s localhost:8080; curl -s localhost:8080
terraform plan -detailed-exitcode >/dev/null; echo "exit=$?"
docker rm -f debug # manual containers must be cleaned up manually
Apply complete! Resources: 2 added, 1 changed, 1 destroyed. unless-stopped Hello from 5e7d1c0a2b33, hits=9 Hello from a41f0c2d9e11, hits=10 exit=0
The counter keeps increasing from its previous value — Redis data lives in a named volume, so adding and removing containers does not affect the data.
Case 1: state committed to a public repository
Problem: An intern pushed terraform.tfstate to a public GitHub repository; it contained database passwords and cloud storage access keys, and was exploited within hours of being scanned. Approach: Rotate all credentials immediately; clean up the Git history; migrate to a remote backend (Azure Storage / S3, with encryption, versioning, and private network access enabled); add the repository to .gitignore and secret scanning (GitHub push protection). Limitations: Cleaning up history cannot retract data that has already been copied; rotation is the only reliable remedy.
Case 2: scheduled drift detection
Problem: Operators often make “temporary” changes to security group rules in the console and forget to write them back to the configuration. Approach: CI runs terraform plan -refresh-only -detailed-exitcode (or a regular plan) every day; on exit code 2, it creates a ticket or sends an alert, attaching the drift details. HCP Terraform provides built-in drift detection (follow the official documentation for version and plan details). Limitations: Only drift in resources tracked in state can be detected; “newly added unmanaged resources” cannot — that requires the cloud platform's resource inventory or Policy.
Case 3: CI cancelled in the middle of an apply
Problem: The CI job timed out and was forcibly killed; some resources were created but state was not yet written (or the lock was not released). Approach: Re-run plan and check for “name already exists” errors; for objects that were created but not recorded, bring them under management with an import block; for a stale lock on a remote backend, release it after confirming that no one is running terraform force-unlock LOCK_ID (Lesson 2). Limitations: Forcibly killing Terraform (SIGKILL) is the worst case; CI should first send SIGINT so Terraform can stop gracefully and write state.
Common errors and fixes
Error: Error acquiring the state lock — resource temporarily unavailable (local terraform.tfstate)
Cause: Another terraform process is using the same working directory (another terminal, an IDE plugin, or a hung process).
ps -ef | grep -v grep | grep terraform
Fix: Wait for or end the other process. Do not casually use -lock=false.
Note: Objects have changed outside of Terraform (the same attribute changes on every plan)
Cause: An external system keeps modifying that attribute, or the provider reads back a value in a different format from the one written (a normalization issue).
Fix: Find and stop the external modification; if it really must be managed externally, use ignore_changes; if it is a provider normalization defect, upgrade the provider or report it in an issue.
Error: Failed to load state: state snapshot was created by Terraform v1.17.2, which is newer than current v1.15.x
Cause: Someone on the team wrote the state with a newer version of Terraform, and the older version refuses to read it.
Fix: Upgrade everyone to the same version; set required_version in the configuration, and pin the version in CI.
Error: Resource instance managed by newer provider version — The current state of docker_container.app[0] was created by a newer provider version than is currently selected.
Cause: The provider was downgraded (the schema_version is newer), or different members use different lock files.
Fix: Restore the version in the lock file (terraform init); make sure the lock file is committed and consistent across the team.
Everything is planned as “will be created”, even though they are running
Cause: State is lost or the command runs in the wrong directory or backend (for example, terraform.tfstate was accidentally deleted, the workspace was switched, or the backend configuration points to a new key).
pwd; ls -la terraform.tfstate*; terraform workspace show; terraform state list | wc -l
Fix:Do not apply. Restore state from terraform.tfstate.backup, or from the history versions in remote storage; if it cannot be restored, bring the resources under management one by one with import blocks.
1. List all docker_container instances in state and their container IDs.
terraform show -json | jq -r '.values.root_module.resources[] | select(.type=="docker_container") | "\(.address) \(.values.id)"'
2. Detect drift only: if there is drift, return exit code 2, and do not modify anything.
terraform plan -refresh-only -detailed-exitcode
Someone used docker update --memory 1g a command to manually increase the memory of the production Redis container for an emergency. How should you handle this drift?
First assess: should the emergency change be kept? If it is kept, change memory in the configuration to 1024 (MB) and submit a PR; the plan should then show No changes (or only a state update), which makes the configuration the source of truth again. If it is not kept, apply during a maintenance window to restore the configured value. Do not just run apply -refresh-only: it only updates state, and the next apply will still change the memory back. Post-incident review: the emergency-change process should include a step to write the change back to the configuration.
Verified teaching videos
Official documentation
- State
- Purpose of Terraform State
- Sensitive Data in State
- terraform state command
- Manage Resource Drift (tutorial)
Video storyboard (about 90 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: a line connects the name app[0] in the configuration with a container ID string in Docker; the midpoint of the line is the state file.
Narration: state is Terraform's memory, recording the correspondence between configuration addresses and real object IDs.
Scene: someone runs docker rm on a container in the terminal; Terraform plan outputs a yellow “Objects have changed outside of Terraform”.
Narration: refreshing before each plan lets you detect drift. plan refresh-only only looks at drift; apply refresh-only writes reality into state; a regular apply changes reality back to the configuration.
Scene: the state file is zoomed in; a password line appears in plaintext, and then it is moved into a locked remote storage icon.
Narration: state contains plaintext secrets, so it must not be committed to Git, and must not be edited by hand. For team collaboration, use a remote backend.
Module 8 · CLI Workflow and Troubleshooting Basics
- Use the standard sequence
init,fmt,validate,plan,apply,destroy, and explain what each step checks, whether it accesses the API, and whether it modifies state. - Use plan files (
plan -out=tfplan→show→apply tfplan) to guarantee that “what is reviewed is what is executed”, and understand “Saved plan is stale”. - Use
-detailed-exitcode(0 no changes / 1 error / 2 changes),-input=false,TF_IN_AUTOMATIONto write CI scripts. - Use
TF_LOGto collect logs, and use the interactive troubleshooting tree to locate common errors by “stage”.
What: the core workflow
| Step | Command | What it checks | Accesses the API? | Writes state? |
|---|---|---|---|---|
| 1 | terraform init | Install providers/modules, configure the backend, verify the lock file | Registry / backend | No (but migrating the backend does) |
| 2 | terraform fmt -check | fmt | No | No |
| 3 | terraform validate | Syntax, references, types, provider schema | No | No |
| 4 | terraform plan -out=tfplan | refresh + diff, generating a plan file | Yes (reads) | No |
| 5 | terraform show tfplan | Human/automated review (-json to a policy tool) | No | No |
| 6 | terraform apply tfplan | Executes strictly per the plan, without asking again | Yes (writes) | Yes |
| — | terraform destroy | Equivalent to apply -destroy: plans to delete all managed resources | Yes | Yes |
Why: why use a plan file
Interactive terraform apply will re- calculate the plan once more. If the plan you saw when reviewing the PR differs from the plan at apply time (someone changed resources in the meantime, an upstream image digest changed, or a data source returned a new value), then what you execute is not what you reviewed. A plan file freezes the change set, the configuration snapshot, the variable values, and the serial of the prior state; if state has been changed by another operation by apply time, Terraform refuses to run (Saved plan is stale), rather than quietly doing something else.
How: exit codes and automation
| Command | Exit code | Meaning |
|---|---|---|
plan -detailed-exitcode | 0 / 1 / 2 | 0 = success with no changes; 1 = error; 2 = success with changes |
| Other commands | 0 / 1 | Success / failure |
fmt -check | 0 / 3 (files need formatting) | Any non-zero requires handling |
-input=false(orTF_INPUT=0): errors when a variable is missing instead of waiting for input.TF_IN_AUTOMATION=1: adjusts the output so there are no human prompts such as “next, run terraform apply”.TF_CLI_ARGS_plan="-parallelism=5": appends arguments to a specific subcommand.-no-color: strips ANSI color codes from log output.-json: makes plan/apply output machine-readable streaming JSON (UI events).-lock-timeout=5m: waits for the state lock instead of failing immediately (commonly used with remote backends).
Logs and crashes
TF_LOG:TRACE/DEBUG/INFO/WARN/ERROR, orJSON(JSON format at TRACE level).TF_LOG_CORE,TF_LOG_PROVIDERcontrol core and provider separately.TF_LOG_PATHWritten to a file.- Generated when Terraform itself panics;
crash.logif a provider process crashes, it displays “The plugin encountered an error, and failed to respond to the plugin.(*GRPCProvider).ApplyResourceChange call”, which is a provider defect; report it to the provider repository with logs attached.
When: the overall approach to troubleshooting
- First see which stage failed: init (download / lock file / backend), validate (syntax / references), plan (refresh, data sources, expression evaluation), apply (API errors: conflicts, permissions, quotas, ports).
- Read the location information in the error: Terraform errors give the file name, line number, and resource address (
on nginx.tf line 5, in resource "docker_container" "nginx"). - Distinguish Terraform errors from API errors: “Error response from daemon: …”, “StatusCode=403”, and similar come from the target platform; reproduce them with that platform's tools (
docker,az,aws). - Turn on logs when necessary:
TF_LOG=DEBUGto see the specific requests and responses.
Comparison with similar technologies
| Terraform | Bicep / az | CloudFormation | Pulumi | |
|---|---|---|---|---|
| Preview | plan | az deployment group what-if | Change set | pulumi preview |
| Execute as previewed | apply tfplan (rejected if stale) | No strict binding | Execute the change set | pulumi up (can be --plan) |
| CI drift detection | -detailed-exitcode | what-if parsing | Drift detection API | preview --expect-no-changes |
-auto-approve is equivalent to applying a plan file”—the former replans and executes directly, with no review guarantee. ③ “It is normal for plan to exit with 0 when there are changes”—without -detailed-exitcode the flag, both no-change and changed runs return 0. ④ “destroy only deletes resources in the configuration”—destroy deletes all managed resources in state.Standard workflow and CI gates
Categorize errors by stage
Interactive: CI-style pipeline simulator
Choose a scenario and then run the pipeline. Each stage shows the real command, output, and exit code; the pipeline decides whether to continue, skip, or fail based on the exit code.
Workflow command quick reference
| Command | Common options | Notes |
|---|---|---|
terraform init | -upgrade -lockfile=readonly -backend=false -reconfigure | Run after any fresh clone, or after changing the provider/module/backend |
terraform fmt | -check -diff -recursive | Format |
terraform validate | -json | Requires init first |
terraform plan | -out=FILE -detailed-exitcode -input=false -var(-file) -refresh-only -destroy -replace -target -parallelism -minimal-refresh (1.17) | Read-only |
terraform show | FILE -json -no-color | View a plan or state |
terraform apply | FILE -auto-approve -refresh-only -replace -lock-timeout | Cannot pass -var |
terraform destroy | -target when a plan file is given (for emergencies only) -auto-approve | = apply -destroy; you can first plan -destroy preview |
terraform output | -json -raw | Module 5 |
cd ~/tf-lab/myapp-stack
terraform plan -input=false -out=tfplan -detailed-exitcode; rc=$?; echo "plan exit=$rc"
terraform show -no-color tfplan | tail -5
terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions != ["no-op"]) | "\(.change.actions | join(",")) \(.address)"'
plan exit=2 Plan: 2 to add, 0 to change, 1 to destroy. create docker_container.app[2] delete,create docker_container.nginx
delete,create indicates a delete-then-create replacement; create,delete indicates a replacement with create_before_destroy. Common errors: In the shell, set -e treats exit code 2 as a failure, so CI scripts must handle it explicitly. Production use: Pass the JSON plan to Terraform Policy / OPA / custom scripts as a gate.
TF_LOG=DEBUG TF_LOG_PATH=debug.log terraform plan -no-color >/dev/null grep -E "\[(ERROR|WARN)\]" debug.log | head ls crash.log 2>/dev/null || echo "no crash"
Lab 8: run plan/apply the way CI does (about 8 minutes)
cd ~/tf-lab/myapp-stack
cat > ci.sh <<'EOF'
#!/usr/bin/env bash
set -uo pipefail
export TF_IN_AUTOMATION=1 TF_INPUT=0
terraform init -input=false -lockfile=readonly >/dev/null || exit 1
terraform fmt -check -recursive || { echo "❌ run terraform fmt first"; exit 1; }
terraform validate -no-color || exit 1
terraform plan -no-color -out=tfplan -detailed-exitcode "$@"
rc=$?
case $rc in
0) echo "✅ no changes"; rm -f tfplan; exit 0 ;;
2) echo "📝 changes; plan saved to tfplan, please review: terraform show tfplan" ;;
*) echo "❌ plan failed"; exit 1 ;;
esac
EOF
chmod +x ci.sh
./ci.sh; echo "ci exit=$?"
Success! The configuration is valid. … No changes. Your infrastructure matches the configuration. ✅ no changes ci exit=0
sed -i 's/^app_replicas = 2/app_replicas = 3/' terraform.tfvars ./ci.sh terraform show tfplan | grep -E "^ #|Plan:"
Plan: 2 to add, 0 to change, 1 to destroy. 📝 changes; plan saved to tfplan, please review: terraform show tfplan # docker_container.app[2] will be created # docker_container.nginx will be replaced due to changes in replace_triggered_by Plan: 2 to add, 0 to change, 1 to destroy.
terraform apply -auto-approve -replace='docker_container.redis' >/dev/null # simulates someone else's action; the state serial changes terraform apply tfplan
╷ │ Error: Saved plan is stale │ │ The given plan file can no longer be applied because the state was changed │ by another operation after the plan was created. ╵
This is exactly what the plan file protects against. Re-run ./ci.sh to generate a new plan, then terraform apply tfplan.
./ci.sh >/dev/null; terraform apply tfplan && rm -f tfplan for i in 1 2 3; do curl -s localhost:8080; done
Apply complete! Resources: 2 added, 0 changed, 1 destroyed. Hello from …-app-0, hits=11 Hello from …-app-1, hits=12 Hello from …-app-2, hits=13
docker run -d --name squatter -p 8081:80 nginx:alpine terraform apply -var 'http_port=8081' -auto-approve 2>&1 | grep -A3 "Error:" docker rm -f squatter terraform apply -auto-approve | tail -1 # back to 8080; the tainted nginx will be replaced
│ Error: Unable to start container: Error response from daemon: … Bind for 0.0.0.0:8081 failed: port is already allocated │ │ with docker_container.nginx, │ on nginx.tf line 10, in resource "docker_container" "nginx":
The error message gives the resource address and file line number; “Error response from daemon” indicates that the Docker API rejected the request. The plan phase did not catch it.
terraform plan -destroy— it will be blocked by the volume's prevent_destroy (Module 4). Keep the environment and move on to the comprehensive lab. To restore app_replicas = 2: sed -i 's/^app_replicas = 3/app_replicas = 2/' terraform.tfvars && terraform apply -auto-approve.Case 1: the plan reviewed in the PR does not match what was executed
Problem: The team saw “1 to change” in the PR; after merging, the pipeline ran apply -auto-approve, but it actually replaced 3 resources (an upstream data source returned a new value in the meantime). Approach: Change the pipeline so that the PR stage runs plan -out and uploads the plan file as an artifact; after approval, the same plan file is apply run with apply; if it has expired, go through approval again. Limitations: A plan file is only valid for the same Terraform version and the same configuration, and it contains secrets, so it needs encrypted storage and a short retention period.
Case 2: nightly drift detection
Problem: We need to know which environments have deviated from the configuration. Approach: A scheduled job runs terraform plan -detailed-exitcode -refresh-only -input=false -lock=false (read-only, so it does not block daytime locks); on exit code 2, it sends show -json a summary of the drift to Teams/Slack. Limitations:-lock=false Suitable only for read-only detection; must never be used for apply.
Case 3: provider crash
Problem: apply reports “The plugin encountered an error, and failed to respond to the plugin.(*GRPCProvider).ApplyResourceChange call”. Approach: Use TF_LOG_PROVIDER=DEBUG to reproduce it; find the provider's panic stack trace in the logs; check the provider issue list to see whether it is already known; temporarily roll back to the previous minor version (a lock file PR), and file an issue with redacted logs in the provider repository. Limitations: Rolling back the provider may run into state schema version issues (see the Module 7 troubleshooting).
Interactive troubleshooting tree: from symptom to fix
Step through the choices based on what you see to get diagnostic commands and fix suggestions. It covers the most common errors across all modules in this lesson.
Supplement: quick overview of high-frequency errors
Error: Saved plan is stale
Cause: State was modified by another operation after the plan.
Fix: Re-plan and re-review; in CI, run plan and apply serially and use a lock (remote locking, Lesson 2).
Error: Inconsistent dependency lock file (when applying tfplan)
Cause: plan and apply ran on different machines with different provider installations.
Fix: Before apply, run terraform init with the same lock file, and keep the Terraform version consistent.
Error: Can't set variables when applying a saved plan
Cause:terraform apply tfplan -var …—the plan file already contains the variable values (in newer versions, passing a value for an ephemeral variable at apply time is an error; the exact wording varies by version, so follow the official documentation).
Fix: Pass variables at plan time; apply only the plan file.
The plugin encountered an error, and failed to respond to the plugin.(*GRPCProvider).PlanResourceChange call
Cause: The provider process crashed (a provider defect or an incompatible configuration).
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=p.log terraform plan; grep -n "panic" p.log | head
Fix: Upgrade or roll back the provider, and report it to the provider repository.
1. Write the command in CI that “generates a plan and decides the next step based on whether there are changes” (without being tripped up by set -e).
set +e terraform plan -input=false -out=tfplan -detailed-exitcode rc=$? set -e [ $rc -eq 1 ] && exit 1 [ $rc -eq 2 ] && echo "has_changes=true" >> "$GITHUB_OUTPUT"
2. List all resources in the plan that will be replaced.
terraform show -json tfplan | jq -r '.resource_changes[] | select((.change.actions|length)==2) | .address'
A new colleague's pipeline is terraform init && terraform apply -auto-approve, please identify at least 4 problems and give an improved set of steps.
Problems: ① no fmt/validate, so errors are found late; ② no review step, so nobody looks at the plan being executed; ③ no -input=false, so it can hang when variables are missing; ④ the plan file is not used, so review (if any) and execution may diverge; ⑤ init is not run with -lockfile=readonly, so the provider may change silently; ⑥ PRs and the main branch are not distinguished. Improvement: in the PR, init -lockfile=readonly → fmt -check → validate → plan -out -detailed-exitcode → publish a plan summary; after merging, approve in a protected environment and apply tfplan.
Verified teaching videos
Official documentation
- CLI Commands
- terraform plan (-out, -detailed-exitcode)
- Running Terraform in Automation
- Debugging Terraform (TF_LOG)
- Environment Variables
Video storyboard (about 90 seconds)
This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.
Scene: six blocks light up in turn: init, fmt, validate, plan, review, apply.
Narration: the standard flow is initialize, format, validate, generate a plan file, review, and finally execute that same plan.
Scene: three exits labeled zero, one, and two lead to “skip”, “fail”, and “review”, respectively.
Narration: with detailed exitcode, zero means no changes, one means an error, and two means changes; CI uses this to route the pipeline.
Scene: during the review, another person ran apply; the plan file is stamped with a red “expired” seal.
Narration: state changed after the plan, so Terraform refuses to run the expired plan, ensuring that what you execute is what you reviewed.
Command cheat sheet
Installation and version (Ubuntu 24.04)
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list sudo apt update && sudo apt install terraform terraform version; terraform version -json terraform -install-autocomplete
Core workflow
terraform init [-upgrade] [-lockfile=readonly] terraform fmt -recursive [-check -diff] terraform validate terraform plan -out=tfplan [-detailed-exitcode] [-input=false] terraform show tfplan # review; -json for tools terraform apply tfplan terraform plan -destroy; terraform destroy
Providers and the lock file
terraform providers terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 terraform providers mirror -platform=linux_amd64 /opt/terraform/providers terraform providers schema -json | jq '.provider_schemas | keys' export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache" # version = "~> 4.7" → >= 4.7.0, < 5.0.0 # version = "~> 4.7.0" → >= 4.7.0, < 4.8.0
Dependencies and lifecycle
depends_on = [docker_container.redis]
lifecycle {
create_before_destroy = true
prevent_destroy = true
ignore_changes = [labels]
replace_triggered_by = [docker_container.app]
}
# terraform apply -replace='docker_container.app[0]'
# terraform graph | dot -Tsvg > graph.svgVariables and outputs
terraform plan -var 'app_replicas=3' terraform plan -var-file=prod.tfvars export TF_VAR_http_port=8081 # precedence: default < TF_VAR_ < terraform.tfvars < *.tfvars.json < *.auto.tfvars < -var/-var-file terraform output terraform output -raw url terraform output -json | jq .
Expressions and console
terraform console
echo 'cidrsubnet("10.20.0.0/16", 8, 1)' | terraform console
# [for c in docker_container.app : c.name]
# { for c in docker_container.app : c.name => c.network_data[0].ip_address }
# docker_container.app[*].name
# var.env == "prod" ? 3 : 1
# try(local.cfg.port, 80) templatefile("x.tftpl", { n = 1 })State and drift
terraform state list terraform state show 'docker_container.app[0]' terraform show -json | jq '.values.root_module.resources[].address' terraform state pull > backup.tfstate terraform plan -refresh-only [-detailed-exitcode] terraform apply -refresh-only # accept reality (writes state only) terraform apply # fix drift (change reality)
Debugging and automation
TF_LOG=DEBUG TF_LOG_PATH=debug.log terraform plan TF_LOG_PROVIDER=DEBUG terraform apply export TF_IN_AUTOMATION=1 TF_INPUT=0 terraform plan -detailed-exitcode # 0 no changes · 1 error · 2 changes terraform plan -minimal-refresh # 1.17: refresh only resources with proposed changes docker ps -a --filter label=managed_by=terraform
Quick troubleshooting table
| Symptom / error | Stage | Most likely cause | First diagnostic command | Module |
|---|---|---|---|---|
| does not have a provider named registry.terraform.io/hashicorp/docker | init | Module not declared source = "kreuzwerker/docker" | terraform providers | M3 |
| locked provider … does not match configured version constraint | init | Constraint changed but lock not upgraded | terraform init -upgrade | M3 |
| doesn't match any of the checksums previously recorded | init | Lock file lacks h1 for the current platform | terraform providers lock -platform=… | M3 |
| Unsupported argument / Did you mean to define a block | validate | Nested block was written as = {} | terraform providers schema -json | M2 |
| Reference to undeclared resource | validate | Typo / subdirectory not loaded | grep -n 'resource "' *.tf | M2 |
| Cycle: … | plan | Mutual references | terraform graph -type=plan | M4 |
| Invalid value for variable | plan | Validation failed | Check tfvars / -var | M5 |
| Instance cannot be destroyed | plan | prevent_destroy | terraform plan See which resource will be deleted | M4 |
| Error pinging Docker server / permission denied … docker.sock | plan/apply | Docker not running / not in docker group | docker info,id -nG | M1 |
| Conflict. The container name … is already in use | apply | Unmanaged object with the same name / CBD + fixed name | docker ps -a --filter name=… | M1/M4 |
| port is already allocated | apply | Host port in use | ss -ltnp | M8 |
| Saved plan is stale | apply | State modified after plan | Re- plan -out | M8 |
| all resources want create | plan | State lost / wrong directory | ls terraform.tfstate*, do not apply | M7 |
Recommended configuration snippets
terraform {
required_version = ">= 1.17.0, < 2.0.0"
required_providers {
docker = { source = "kreuzwerker/docker", version = "~> 4.7" }
random = { source = "hashicorp/random", version = "~> 3.9" }
}
}
.terraform/ *.tfstate *.tfstate.* *.tfplan tfplan crash.log *.auto.tfvars # if it contains secrets # commit: *.tf .terraform.lock.hcl *.tfvars without secrets
Comprehensive lab + final quiz
Your team has decided to stop managing demo environments with “runbook + docker run”. Deliver a Terraform root module: standard file structure, locked providers (with hashes for the team's three platforms), parameterization (replica count, port), stateful data protected, sensitive values never shown on screen, and the access address as output; and demonstrate: ① drift is detected and repaired; ② there is a Terraform invisible drift, and how to handle it.
cd ~/tf-lab/myapp-stack
# 1) Remove prevent_destroy (a separate step, to understand that deletion protection must be removed explicitly)
sed -i '/lifecycle {/,/}/d' network.tf && grep -n prevent_destroy network.tf || echo "protection removed"
terraform destroy -auto-approve | tail -1
docker ps -a --filter name=myapp-dev --format '{{.Names}}' | wc -l # 0
This sed deletes the only lifecycle block in network.tf; if you added other content there, edit it manually. nginx:alpine,redis:7-alpine the image is kept because of keep_locally so there is no need to download it again below.
~/tf-lab/final (full files, can be copied as a whole)
mkdir -p ~/tf-lab/final && cd ~/tf-lab/final
cat > versions.tf <<'EOF'
terraform {
required_version = ">= 1.17.0, < 2.0.0"
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 4.7"
}
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}
EOF
cat > providers.tf <<'EOF'
provider "docker" {
host = "unix:///var/run/docker.sock"
}
EOF
cat > variables.tf <<'EOF'
variable "project" {
type = string
default = "myapp"
}
variable "env" {
type = string
default = "dev"
validation {
condition = contains(["dev", "prod"], var.env)
error_message = "env must be dev or prod."
}
}
variable "app_image" {
type = string
default = "myapp:1.0"
}
variable "app_replicas" {
type = number
default = 2
nullable = false
validation {
condition = var.app_replicas >= 1 && var.app_replicas <= 5
error_message = "app_replicas must be between 1 and 5."
}
}
variable "http_port" {
type = number
default = 8080
validation {
condition = var.http_port > 1024 && var.http_port < 65536
error_message = "Please use a port between 1025 and 65535."
}
}
variable "subnet" {
type = string
default = "10.20.0.0/24"
validation {
condition = can(cidrhost(var.subnet, 1))
error_message = "subnet must be a valid CIDR."
}
}
EOF
cat > locals.tf <<'EOF'
locals {
name_prefix = "${var.project}-${var.env}"
common_labels = {
project = var.project
env = var.env
managed_by = "terraform"
}
}
EOF
cat > network.tf <<'EOF'
resource "docker_network" "app" {
name = "${local.name_prefix}-net"
ipam_config {
subnet = var.subnet
}
}
resource "docker_volume" "redis_data" {
name = "${local.name_prefix}-redis-data"
lifecycle {
prevent_destroy = true # Redis data: must be explicitly removed before deletion
}
}
EOF
cat > redis.tf <<'EOF'
resource "docker_image" "redis" {
name = "redis:7-alpine"
keep_locally = true
}
resource "docker_container" "redis" {
name = "${local.name_prefix}-redis"
image = docker_image.redis.image_id
restart = "unless-stopped"
command = ["redis-server", "--appendonly", "yes"]
networks_advanced {
name = docker_network.app.id
aliases = ["redis"]
}
volumes {
volume_name = docker_volume.redis_data.name
container_path = "/data"
}
dynamic "labels" {
for_each = local.common_labels
content {
label = labels.key
value = labels.value
}
}
}
EOF
cat > app.tf <<'EOF'
data "docker_image" "myapp" {
name = var.app_image
}
resource "random_password" "app" {
length = 24
special = false
}
resource "docker_container" "app" {
count = var.app_replicas
name = "${local.name_prefix}-app-${count.index}"
image = data.docker_image.myapp.id
restart = "unless-stopped"
env = ["REDIS_HOST=redis", "APP_SECRET=${random_password.app.result}"]
networks_advanced {
name = docker_network.app.id
aliases = ["app"]
}
healthcheck {
test = ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz')"]
interval = "10s"
timeout = "3s"
retries = 3
}
dynamic "labels" {
for_each = local.common_labels
content {
label = labels.key
value = labels.value
}
}
depends_on = [docker_container.redis] # accessed only by the DNS name redis, so an explicit dependency is needed
}
EOF
cat > nginx.conf.tftpl <<'EOF'
upstream myapp {
%{ for name in upstreams ~}
server ${name}:5000;
%{ endfor ~}
}
server {
listen 80;
location = /nginx-health { return 200 "ok\n"; }
location / { proxy_pass http://myapp; }
}
EOF
cat > nginx.tf <<'EOF'
data "docker_registry_image" "nginx" {
name = "nginx:alpine"
}
resource "docker_image" "nginx" {
name = "nginx:alpine"
keep_locally = true
pull_triggers = [data.docker_registry_image.nginx.sha256_digest]
}
resource "docker_container" "nginx" {
name = "${local.name_prefix}-nginx"
image = docker_image.nginx.image_id
restart = "unless-stopped"
ports {
internal = 80
external = var.http_port
}
networks_advanced {
name = docker_network.app.id
}
upload {
file = "/etc/nginx/conf.d/default.conf"
content = templatefile("${path.module}/nginx.conf.tftpl", {
upstreams = docker_container.app[*].name
})
}
dynamic "labels" {
for_each = local.common_labels
content {
label = labels.key
value = labels.value
}
}
lifecycle {
replace_triggered_by = [docker_container.app]
}
}
EOF
cat > outputs.tf <<'EOF'
output "url" {
value = "http://localhost:${var.http_port}"
}
output "app_ips" {
value = { for c in docker_container.app : c.name => c.network_data[0].ip_address }
}
output "app_secret" {
value = random_password.app.result
sensitive = true
}
EOF
cat > terraform.tfvars <<'EOF'
app_replicas = 2
http_port = 8080
EOF
printf '.terraform/\n*.tfstate\n*.tfstate.*\ntfplan\ncrash.log\n' > .gitignore
lsterraform init terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 terraform fmt -check -recursive && terraform validate
terraform plan -input=false -out=tfplan -detailed-exitcode; echo "exit=$?"
terraform show -json tfplan | jq -r '.resource_changes[] | "\(.change.actions|join(",")) \(.address)"'
terraform apply tfplan && rm -f tfplan
Plan: 9 to add, 0 to change, 0 to destroy.
exit=2
create docker_container.app[0]
create docker_container.app[1]
create docker_container.nginx
create docker_container.redis
create docker_image.nginx
create docker_image.redis
create docker_network.app
create docker_volume.redis_data
create random_password.app
…
Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
Outputs:
app_ips = {
"myapp-dev-app-0" = "10.20.0.3"
"myapp-dev-app-1" = "10.20.0.4"
}
app_secret = <sensitive>
url = "http://localhost:8080"
9 managed resource instances: network, volume, 2 images, redis container, 2 app containers (count = 2 counts as two instances), nginx container, random_password. The two data sources are read during the plan phase and are not counted.
for i in 1 2 3 4; do curl -s "$(terraform output -raw url)"; done
curl -s localhost:8080/nginx-health
docker ps --filter label=managed_by=terraform --format 'table {{.Names}}\t{{.Status}}'
terraform plan -detailed-exitcode >/dev/null; echo "drift-check exit=$?"
Hello from 0c1d…, hits=1 Hello from 7e2f…, hits=2 Hello from 0c1d…, hits=3 Hello from 7e2f…, hits=4 ok NAMES STATUS myapp-dev-nginx Up 30 seconds myapp-dev-app-1 Up 32 seconds (healthy) myapp-dev-app-0 Up 32 seconds (healthy) myapp-dev-redis Up 34 seconds drift-check exit=0
docker rm -f myapp-dev-app-1
docker update --restart=no myapp-dev-redis
terraform plan -refresh-only -detailed-exitcode | grep -E "has been deleted|has changed|restart"; echo "exit=${PIPESTATUS[0]}"
terraform plan -out=tfplan | grep -E "^ #|Plan:"
terraform apply tfplan && rm -f tfplan
terraform plan -detailed-exitcode >/dev/null; echo "after-fix exit=$?"
# docker_container.app[1] has been deleted
# docker_container.redis has changed
~ restart = "unless-stopped" -> "no"
exit=2
# docker_container.app[1] will be created
# docker_container.nginx will be replaced due to changes in replace_triggered_by
# docker_container.redis will be updated in-place
Plan: 2 to add, 1 to change, 1 to destroy.
Apply complete! Resources: 2 added, 1 changed, 1 destroyed.
after-fix exit=0
The counter continues to increase after the repair (Redis data is in the protected volume).
docker exec myapp-dev-nginx sh -c 'sed -i "/app-1/d" /etc/nginx/conf.d/default.conf && nginx -s reload' for i in 1 2 3 4; do curl -s localhost:8080; done # only app-0 is still responding terraform plan -detailed-exitcode >/dev/null; echo "exit=$?" # 0!
Hello from 0c1d…, hits=9 Hello from 0c1d…, hits=10 Hello from 0c1d…, hits=11 Hello from 0c1d…, hits=12 exit=0
Why can't it be seen?upload The file is written only when the container is created; the provider's ReadResource does not read back the file contents inside the container, so state holds the “last uploaded content” and refresh cannot compare them. Fix: terraform apply -replace=docker_container.nginx. Lesson: Terraform can only detect attributes the provider can read back; configuration drift inside a container or VM requires immutable deployment (rebuild rather than modify), configuration management tools (Ansible, the second course), or runtime monitoring.
terraform apply -replace=docker_container.nginx -auto-approve | tail -1 for i in 1 2; do curl -s localhost:8080; done
terraform plan -var 'app_replicas=9' 2>&1 | grep -A1 "Error:" # validation blocks it terraform apply -var 'app_replicas=3' -auto-approve | tail -1 # scale out; nginx updates automatically terraform output app_ips terraform plan -destroy 2>&1 | grep "Instance cannot be destroyed" # the volume is protected terraform output app_secret # <sensitive> terraform state list | wc -l
terraform state rm docker_volume.redis_data before destroy — this makes Terraform “stop managing” without deleting the volume; Lesson 2 does this more properly with an removed block):
sed -i '/lifecycle {/,/}/d' network.tf
terraform destroy -auto-approve | tail -1
docker ps -a --filter label=managed_by=terraform -q | wc -l # 0
docker volume ls --filter name=myapp-dev # already deleted
The local Docker lab incurs no cloud costs at all. Lesson 2 builds on this by introducing remote state (MinIO simulating S3), modules, and import; please keep the ~/tf-lab/final directory.
Open-ended self-test (answer first yourself, then expand the reference answer)
1. Describe a single terraform apply run: the main gRPC calls between core and provider, in order.
Start the plugin process and handshake → GetProviderSchema → ValidateProviderConfig/ValidateResourceConfig → (after reading state) UpgradeResourceState → ConfigureProvider → refresh phase ReadResource (and ReadDataSource) → each resource PlanResourceChange → after confirmation, execute in parallel per the dependency graph ApplyResourceChange, writing state as each completes → the plugin exits.
2. What problem does each of the version constraint and the lock file solve? Why must the team commit the lock file?
The constraint declares the “allowed range”; the lock file records the “version actually selected and its package hashes”. Committing the lock file ensures everyone and CI install the same version and can verify the package has not been tampered with; upgrades go through init -upgrade to form a reviewable diff.
3. When is depends_on needed? What is the cost of overusing it?
When a dependency cannot be expressed through a reference (for example, via a DNS name or the order in which permissions take effect). Cost: lower parallelism; on a data source it defers the read, causing many unknown values and unexpected replacements in the plan.
4. sensitive = true What can it protect, and what can't it?
It prevents values from appearing in the terminal output of plan/apply/output; it cannot prevent them from being stored in plaintext in state and plan files,output -json which can also be read. Protect state access permissions, and use ephemeral/write-only where necessary.
5. apply -refresh-only Versus ordinary apply the difference in handling drift?
The former writes the real world's current value into state without changing the real object (accept reality); the latter converges the real world to the configuration (fix drift). If you only do the former and do not change the configuration, the next ordinary apply will still change reality back to the configuration.
6. Why should production pipelines apply a plan file instead of apply -auto-approve?
The plan file guarantees that what is executed is exactly the change that was reviewed; if state changes during review, Terraform refuses to execute it (Saved plan is stale). -auto-approve will re-plan and execute directly, so the review becomes meaningless.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Terraform CLI version | Latest v1.17.2 (2026-11-11); 1.17.1 (2026-10-28); 1.17.0 (2026-10-21); the latest 1.16.x patch is 1.16.7 | releases.hashicorp.com/terraform · v1.17 CHANGELOG |
| New features in 1.17 | provider requirements support variable/local; -minimal-refresh; Terraform Policy GA (-policies, plan/apply/query); terraform test 's mock_provider supports ephemeral resources; version -json added format_version | v1.17 CHANGELOG |
| Installation method | HashiCorp apt repository command (keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg, UBUNTU_CODENAME detected automatically); the page shows the latest version 1.17.2 | Install Terraform |
| kreuzwerker/docker | Latest 4.7.0 (2026-11-11); 4.0.0 (2026-04-03) introduced the Plugin Framework mux and buildx by default; 4.6.0 changed the healthcheck to recreate the container; docker_image arguments name/keep_locally/pull_triggers/build/platform, attributes image_id/repo_digest; data "docker_image" reads locally existing images | Registry · CHANGELOG |
| hashicorp/random, local | random 3.9.1 (2026-09-11); local 2.9.1 (2026-09-10) | random · local |
| Other providers / tools (later courses) | azurerm latest 5.14.0 (5.x); aws 6.73.0; OpenTofu 1.13.9 | Registry / OpenTofu releases (verified by the course coordinator, 2026-11) |
| Plugin architecture | Providers are separate processes that communicate over gRPC (plugin protocol v5/v6); RPCs: GetProviderSchema, Validate*Config, ConfigureProvider, UpgradeResourceState, ReadResource, ReadDataSource, PlanResourceChange, ApplyResourceChange, ImportResourceState | Plugin Protocol · How Terraform Works |
| Lock file and provider installation | h1/zh hashes,providers lock -platform, plugin cache and provider_installation | Dependency Lock File · CLI Config |
| Language | variable precedence, types, validation, lifecycle, for expressions, functions | Terraform Language |
| State and drift | state structure, sensitive data, refresh-only | State · Resource Drift |
| CLI and automation | -detailed-exitcode (0/1/2), plan files, TF_LOG, TF_IN_AUTOMATION | plan · Debugging · Env Vars |
Video verification notes
The following videos were verified on 2026-11-15 via the YouTube oEmbed API to have matching titles and channels: Fireship “Terraform in 100 Seconds” (tomUWcQ0P3k); TechWorld with Nana “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE); HashiCorp, an IBM Company “Introduction to HashiCorp Terraform with Armon Dadgar” (h970ZBgKINg); freeCodeCamp.org “HashiCorp Terraform Associate Certification Course (003) - Pass the Exam!” (SPcwo0Gq9T8) and “HashiCorp Terraform Associate Certification Course - Pass the Exam!” (V4waklkBC38); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); KodeKloud “Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide!” (YcJ9IeukJL8). The oEmbed API does not return durations or publish dates, so no specific durations are given on the cards (the Fireship series runs about 2 minutes, which is that series' convention). No verified dedicated videos were found for lock files, lifecycle, or for expressions, so storyboard scripts are provided instead. All videos are in English and were recorded before Terraform 1.17; for version details, follow this lesson and the official documentation.
Voice narration notes
The “Voice” page uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration aloud in real time; English terms are pronounced with en-US; the result depends on the speech pack installed on the system. The courseware generation environment cannot call TTS services, so no MP3 is embedded; if offline audio is needed, the narration script can be passed to a service such as Azure AI Speech to generate it.
Known limitations
- The commands in this courseware were not actually executed in the generation environment; container IDs, image digests, IPs, PIDs, key IDs, serials, counter values, and times in the “expected output” are sample values; some CLI output is excerpted, and the exact text may differ slightly between Terraform / provider minor versions.
- The attributes shown in the provider plan (for example
docker_containerhave dozens of computed attributes) are heavily abbreviated in the examples. - The conclusion of “drift B” (
uploadcontent is not read back for comparison) is based on how the provider is implemented; if a future version changes this behavior, follow the actual plan output. - The 1.17 note that “provider requirements can use variable/local” is based only on the CHANGELOG description; for specific restrictions, follow the official documentation. This lesson does not use that syntax.
- The step breakdown, log lines, and timings in the animations are illustrative, used to explain the real mechanism, and are not byte-for-byte TF_LOG output.
- Docker Hub anonymous access has rate limits,
docker_registry_imageso data sources may hit 429 when plan is run frequently.