Terraform Hour 1: Core Fundamentals

From “typing docker run by hand” to “a reviewable, replayable declarative configuration”: architecture, HCL, providers, dependencies, variables, functions, state, and the CLI workflow
Terraform v1.17.2kreuzwerker/docker 4.7.0hashicorp/random 3.9.1Free local labVerified against official documentation · 2026-11
Overall learning objectives
  • 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 / ApplyResourceChange and other calls.
  • Read and write fluently HCL: terraform / provider / resource / data / variable / output / locals / module eight block types, expressions, functions, and for expressions.
  • Use required_providers version constraints and .terraform.lock.hcl the lock file so that teams and CI get exactly the same provider, handle multi-platform providers 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-only to handle drift.
  • Follow fmt → validate → plan -out → apply plan file the standard workflow, and use -detailed-exitcode for CI drift detection, and diagnose the dozen or so most common error types.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (local Docker)
0Before classEnvironment setupInstall Terraform 1.17 on Ubuntu 24.04 (HashiCorp apt repository), and confirm Docker 29 and the myapp imageEnvironment self-check listterraform version,docker info
100–06IaC and Terraform ArchitectureDeclarative vs. imperative, tool comparison, core + provider gRPC, dependency graph, BSL and OpenTofuThe full mechanics of a single terraform apply (core animation)Your first docker_container
206–13HCL Syntax and Core Blocks8 block types, arguments and nested blocks, types, expressions, interpolation, comments, file organization conventionsHCL block dissector (click to highlight)Split the stack into a standard file structure
313–19Providers and the Lock Filerequired_providers, version constraint operators, init installation flow, lock file h1/zh hashes, multi-platform locks, caching and mirrorsVersion constraint solverLock file + plugin cache
419–27Resources, Dependencies, and Lifecycleimplicit/explicit dependencies, parallelism, create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by, -replaceDependency graph and replacement-order simulatorFull nginx + myapp + redis stack
527–34Variables, Outputs, Localstype system, default values, validation, sensitive, nullable, tfvars precedence, TF_VAR_Variable precedence calculatorSwitching between dev and prod tfvars
634–41Data Sources and Expression Functionswhen data blocks are read, common functions, for/splat/conditional expressions, dynamic blocks,terraform consolefor expression labAutomatically update images by digest
741–50State Basicsthe purpose and structure of state, serial/lineage, sensitive data, state list/show, refresh-only, and why not to edit by handConfiguration · state · real world: three-way comparison (drift)Create and fix drift
850–60CLI Workflow and Troubleshooting Basicsinit/fmt/validate/plan/apply/destroy, plan files,-detailed-exitcode, TF_LOG, common errorsCLI pipeline + interactive troubleshooting treeCI-style plan/apply
—After classCheat sheet · Comprehensive labUse Terraform to manage the complete local myapp stack, demonstrating drift and repairFinal quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLabs
Explain IaC and Terraform architecture✓·✓✓··✓·terraform graph,TF_LOGM1 first container
Read and write HCL configuration·✓·✓✓✓··terraform fmt,validateRefactor file structure
Manage provider versions and the lock file··✓····✓init -upgrade,providers lockMulti-platform lock
Model resource dependencies and lifecycle✓··✓·✓··apply -replace,graphFull stack + replacement
Parameterization and outputs·✓··✓✓··-var-file,output -jsondev/prod
Query external data, write expressions····✓✓··terraform consolePull triggered by digest
Understand and inspect state✓···✓·✓✓state list/show,show -jsondrift
Drift detection and repair···✓··✓✓plan -refresh-only,-detailed-exitcodeComprehensive lab
Standard CLI workflow and troubleshooting··✓···✓✓plan -out,apply tfplanM8 lab

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

TopicWhy not in this lessonWhere to learn
remote backend (S3 + use_lockfile, azurerm), state locking, workspaces,import/moved/removed blocks, writing modulesBelongs to “Team collaboration and production readiness”Lesson 2(simulating S3 with a MinIO container)
azurerm 5.x (latest 5.14.0), authentication, Container Apps / VMsRequires a cloud subscription and incurs costsLesson 3 (Azure)
aws 6.x (latest 6.73.0), VPC, ECS FargateSame as aboveLesson 4 (AWS)
GitHub Actions + OIDC, HCP Terraform, Terraform Policy (1.17 GA),terraform testBelongs to automation and operationsLesson 5
ephemeral resources, write-only arguments,check blocks, StacksDepends on the fundamentals in this lessonLessons 2, 5, 6
Performance tuning (-parallelism, splitting large state), in-depth troubleshootingRequires a larger-scale environmentLesson 7

How to use this courseware

10 pages per module
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.
Learning progress
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).
Chinese voice
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.
Prerequisite course This lesson assumes you have completed Docker 8-hour course, and are familiar with 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.
Version notes This lesson uses Terraform v1.17.2 (2026-11-11) as its baseline; 1.17.0 (2026-10-21) added: variables and locals can be used in provider requirements,-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)

Install Terraform 1.17 on Ubuntu 24.04 from the official HashiCorp apt repository, and confirm that Docker Engine and the myapp image are available
Before class ≈ 10 minTerraform 1.17.2Docker Engine 29
Prerequisites
  • 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 docker group (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
Pin the version When the team and CI must use the same minor version, you can 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.
WSL2 / native Windows Install Ubuntu 24.04 in WSL2 with the same commands; Docker Desktop needs WSL integration enabled so that /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
Why build by hand first The Docker provider's 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…).

Environment self-check list

Module 1 · IaC and Terraform Architecture

00:00 – 06:00 · You describe “what you want”, and Terraform works out “how to do it”: core builds the dependency graph, and provider plugins call the real APIs over gRPC
6 minTerraform 1.17 · plugin protocol v5/v6★★★★★
Learning objectives
  • 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 apply full 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.
Prerequisites: docker run / network / volume from the Docker course. Importance:★★★★★ (every later module builds on this mental model)

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.

ImperativeDeclarative
You writeSteps: create the network first, then start redis, then start the appResult: there should be 1 network, 1 redis, and 2 apps
Re-runningThe second run reports “name already in use”, so you have to write your own if checksWith no differences, nothing is done (No changes)
ModifyingYou have to write a script that deletes the old and creates the newChange configuration → Terraform computes the diff (in-place update or replacement)
DeletingYou need a separate cleanup script, which is easy to get wrongRemove the block from the configuration, or terraform destroy
Examplesbash + docker run,az/aws CLI scriptsTerraform, Bicep, CloudFormation, Kubernetes YAML, Compose

Why: why Terraform is needed

  • Reviewable: terraform plan Gives 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 terraform binary): 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 is terraform init downloaded 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 calledPurpose
GetProviderSchemaAt the start of each commandReturns the schema of the provider/resource/data source (attributes, types, whether Computed/ForceNew)
ValidateProviderConfig / ValidateResourceConfigvalidate, planValidates arguments without calling the API
ConfigureProviderBefore API access is neededPasses in the provider block's configuration (such as the Docker host or cloud credentials), and the provider sets up its client
UpgradeResourceStateAfter reading stateUpgrades state from an older schema version to the current schema
ReadResourceRefresh phaseReads real objects by the IDs in state and detects drift
ReadDataSourceplan (or apply, depending on whether the arguments are known)Runs data block queries
PlanResourceChangeplanInput: prior state + configuration + the proposed new state synthesized by core; output: planned state (unknown values marked as known after apply) and RequiresReplace paths
ApplyResourceChangeapplyActually calls the API to create/update/delete, returns the new state, which core writes to state
ImportResourceStateimportBrings 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)

TerraformOpenTofuPulumiBicepCloudFormationAnsible
LanguageHCLHCL (highly compatible with Terraform)TS/Python/Go/C#/Java/YAMLBicep DSL → ARM JSONYAML/JSONYAML playbook
ParadigmDeclarativeDeclarativeDeclarative results, written in an imperative languageDeclarativeDeclarativeMainly procedural (the modules themselves are mostly idempotent)
Statestate file (local / remote backend / HCP Terraform)Same as left, and also supports client-side state encryptionPulumi Cloud or a self-managed backendNo separate state; Azure deployment history; Deployment Stacks manage the lifecycleAWS-managed stackNo state (queries the target machine every time)
PlatformAny (provider ecosystem)Any (most providers are common)AnyAzure onlyAWS onlyAny (leans toward configuration management)
LicenseBSL 1.1 (from 1.6)MPL 2.0, a Linux Foundation projectApache 2.0 (engine)MITAWS servicesGPL v3
Typical usesMulti-cloud infrastructureSame as left, prefers an open-source licenseTeams whose developers know general-purpose languagesPure Azure teamsPure AWS teamsSystem 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.

Common misconceptions① “Terraform is cross-cloud, so one configuration can deploy to Azure and AWS at the same time”—the workflow is cross-cloud, but resource types are platform-specific (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

Configuration *.tf versions.tf / main.tfvariables.tf / outputs.tf*.tfvars.terraform.lock.hcl Terraform core (terraform binary) HCL parsing / evaluation Dependency graph DAG diff / plan calculation Graph walk (10 in parallel) State management (read / write / lock / backup) terraform.tfstate (or remote backend)Resource address ↔ real ID + attributes + dependencies terraform-provider-docker 4.7.0Child process · gRPC (plugin protocol) terraform-provider-random 3.9.1Purely local logic, no external API terraform-provider-azurerm / aws …Lessons 3, 4 gRPC Docker EngineREST API/var/run/docker.sock Azure ARM / AWSHTTPS API
Figure 1-1: core only understands schemas and the dependency graph; each provider is a separate process responsible for translating “resource changes” into API calls for its specific platform

Dependency graph: the DAG of this lesson's myapp stack

docker_network.app docker_volume.redis_data docker_image.redis docker_image.myapp docker_container.redis docker_container.app[0..1] docker_image.nginx docker_container.nginx output Dashed line: depends_on Arrow direction = “what gets created first”. Nodes in the same column with no dependency between them run in parallel; destruction runs in the opposite direction
Figure 1-2: core derives edges from expression references (such as docker_network.app.id) derives edges; depends_on adds hidden dependencies

Core 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.

CLIterraform apply *.tf + lockHCL parsing Terraform core Dependency graph · diff · traversal network image container terraform.tfstateserial — provider plugin processterraform-provider-dockergRPC server— Docker Engine API/var/run/docker.sock—
Ready.
$ terraform apply
Key points① On every command, the provider is started anew as a child process; it exits when the command ends and does not keep state itself; ② state is updated for each resource as it completes (not written once at the end), so if apply fails midway, completed resources are still recorded in state; ③ unknown values in the plan phase (known after apply) are filled in during apply by ApplyResourceChange return values, which are then passed on to downstream resources.

Commands covered in this module

CommandPurposeKey options / notes
terraform versionView the core and installed provider versions-json (since 1.17, JSON includes format_version field)
terraform initInitialize the working directory: install providers and modules, configure the backendModule 3 details
terraform planCompute the execution plan (does not change real resources)-out,-refresh-only,-destroy
terraform applyPlan + confirm + execute-auto-approve,-parallelism=N (default 10)
terraform graphOutput 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)

Create the working directory and configuration
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
  }
}
EOF
init: download the provider
terraform 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.

plan: see what Terraform intends to do
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.

apply and verify
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
Idempotency: apply again
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.
Change one argument and observe the “replacement”: change 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.

Cleanup (the next module will create a new project directory):
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).

Command-line tasks
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
Scenario analysis
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

▶
Terraform in 100 Seconds — Fireship
English · about 2 minutes · quickly builds an overall picture of “declarative + provider + state”
▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · architecture (core / provider), declarative model, differences from Ansible
▶
Introduction to HashiCorp Terraform with Armon Dadgar — HashiCorp, an IBM Company
English · a HashiCorp co-founder explains Terraform's original design intent and the write → plan → apply workflow (recorded earlier; follow this lesson for version details)

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.

Shot 1 · 0–15s
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.
Shot 2 · 15–40s
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.
Shot 3 · 40–70s
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.
Shot 4 · 70–90s
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.
or reach ≥ 70% on the quiz

Module 2 · HCL syntax and core blocks

06:00 – 13:00 · Everything is a “block”: block type + labels + body; the body contains arguments, nested blocks, and expressions
7 minHCL2 · Terraform 1.x syntax is stable★★★★★
Learning objectives
  • 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 as TYPE.NAME the reference rules for resource addresses.
  • Use string interpolation, heredocs, conditional expressions, and comments, and organize files according to the official style guide.
Prerequisites: The labs from Module 1. Importance:★★★★★

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"
  }
}
BlockLabelPurposeReference
terraformNoneSet by Terraform itself: required_version,required_providers,backend,cloud—
providerprovider local nameConfigure the provider (API endpoint, region, credentials); can use alias to define multiple instancesprovider = docker.remote
resourcetype, nameDeclare an infrastructure object whose lifecycle is managed by Terraformdocker_container.redis.id
datatype, nameRead-only query of existing external objects or computed results (Module 6)data.docker_network.ext.id
variablenameInput parameters (Module 5)var.env
outputnameOutput values, for people, parent modules, or other configurationsmodule.net.network_id (from the parent module)
localsNoneNamed intermediate values (you can have multiple locals blocks)local.name_prefix (note: singular)
modulenameCalls 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,for Expressions 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 fmt can 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

CategorySyntaxExample
Primitive typesstring / number / bool / null"redis",6379,true,null (equivalent to “not writing this argument”)
Collectionslist/tuple [ ], map/object { }["a", "b"],{ env = "dev", tier = "web" }
ReferencesTYPE.NAME.ATTR,var.,local.,data.,module.docker_image.redis.image_id
Special referencespath.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
OperatorsArithmetic, comparison, logical && || !var.replicas > 1
Conditionalcond ? a : bvar.env == "prod" ? 3 : 1
Functionsname(args), only built-in functions and provider functions can be usedupper(var.env),merge(a, b)
for / splat[for x in list : …],list[*].attrModule 6

Difference between arguments, nested blocks, and meta-arguments

  • Argument: name = "x", defined by the provider schema (docker_container 's name,image,env…).
  • Nested block: ports { … }, also defined by the schema, and can appear multiple times (one block per port mapping). It cannot be written as ports = { … }.
  • 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.json files 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 a module block).
  • Files recommended by the official style guide: terraform.tf (or versions.tf) hold the terraform block; providers.tf; main.tf (or split by domain into network.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 (write docker_network.app, not docker_network.app_network; indent arguments by 2 spaces and align equals signs at the same level (handled by terraform fmt).
  • override.tf / *_override.tf override 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)BicepCloudFormation YAMLPulumi
Referencesdocker_network.app.idvnet.id!Ref / !GetAttobject attributes net.id (Output type)
Loopscount / for_each / for[for … ]Limited (macros / Fn::ForEach)Native language loops
Custom functionsNot supported (only built-in and provider functions)Supports user-defined functionsNoneNative language
Formatting toolterraform fmtbicep formatcfn-lintBuilt into the language
Common misconceptions① “Files have a loading order, so variables must be defined first”—there is no order: Terraform reads all files first, then evaluates them according to the dependency graph. ② “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

resource "docker_container" "redis" { name = "${local.name_prefix}-redis" image = docker_image.redis.image_id restart = "unless-stopped" networks_advanced { name = docker_network.app.id aliases = ["redis"] } } Block type resource · label 1 = type · label 2 = name Argument: string interpolation referencing a local Argument: resource reference → implicit dependency Nested block: no equals sign, can repeat Address: docker_container.redis
Figure 2-1: resource block = type + name + body; the type prefix (docker_) determines which provider handles it

File organization: one directory is one module

~/tf-lab/myapp-stack/ (root module) versions.tf terraform { required_* } providers.tf provider "docker" { } variables.tf variable blocks locals.tf locals { } network.tf network / volumes redis.tf · app.tf · nginx.tf outputs.tf output blocks terraform.tfvars · .terraform.lock.hcl Merged into one configurationOrder doesn't matterNames must be globally unique Not loaded automaticallySubdirectory modules/…Must be called with a module block Commit to Git?✓ *.tf ✓ .terraform.lock.hcl✗ .terraform/ ✗ *.tfstate*✗ *.tfvars containing secrets
Figure 2-2: file names are only a convention; Terraform only cares about the directory. .terraform/ and state must not be committed

Interactive: 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.


        
Click a highlighted fragment in the code on the left.
core evaluation log

Syntax-related commands

CommandPurposeKey options
terraform fmtFormat the .tf/.tfvars in the current directory to the canonical style-recursive,-check (for CI; returns non-zero when differences exist),-diff
terraform validatesyntax + type + schema validation (no API access, does not read state)-json; requires init first (needs the provider schema)
terraform consoleEvaluate expressions interactivelyModule 6
terraform providers schema -jsonExport the schema of all resourcesAuthoritative 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.

Create the directory and versions.tf / providers.tf
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
EOF
variables.tf and locals.tf
cat > 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"
  }
}
EOF
network.tf and redis.tf
cat > 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
    }
  }
}
EOF
outputs.tf, then init / fmt / validate / apply
cat > 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.

Verify
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-net
Exercise: deliberately make a mistake and read the error: change networks_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}]' *.tf

Fix: Replace them with ASCII quotes and spaces, then run terraform fmt (fmt refuses to format on syntax errors and reports the line number).

Command-line tasks
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'
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · a long full course; the HCL syntax and variables/modules chapters can extend this module and Lesson 2
▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · a beginner tutorial with labs; HCL basics and resource/variable blocks

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
or reach ≥ 70% on the quiz

Module 3 · Providers and the Lock File

13:00 – 19:00 · Version constraints decide “which versions are allowed”; the lock file decides “which exact version and package to use”
6 minDependency lock file (since 0.14)1.17: provider requirements can use variable/local★★★★☆
Learning objectives
  • Write a correct required_providers: local name,source address ([hostname/]namespace/type),version constraints, and required_version.
  • Explain terraform init the provider installation process (Registry discovery → download → GPG signature and checksum verification → extract to .terraform/providers).
  • Read .terraform.lock.hcl in h1: and zh: hashes, and use init -upgrade to upgrade, and providers lock -platform to fill in hashes for multiple platforms.
  • Configure the plugin cache TF_PLUGIN_CACHE_DIR and provider_installation (filesystem mirror / network mirror), to cope with offline and restricted network environments.
Prerequisites: Modules 1–2. Importance:★★★★☆ (the foundation for team collaboration and CI stability)

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 is registry.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 assume hashicorp/<local name>, which for docker means it will look for a non-existent hashicorp/docker (item 1 in the troubleshooting section).

Version constraint operators

SyntaxMeaningWhen to use
= 4.7.0 or 4.7.0Exact version (the only way to match a pre-release version)Temporarily pin to reproduce a problem
!= 4.6.0Exclude a specific defective versionCombine with other conditions
> >= < <=CompareSet the minimum version for a reusable module >= 4.0
~> 4.7Pessimistic constraint: only the rightmost segment is allowed to increase → >= 4.7.0, < 5.0.0Recommended 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.1A 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 official SHA256SUMS file 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, use terraform providers lock -platform=….
  • The lock file locks only providers, not module versions (module versions are pinned in the module block's version ).

How: terraform init the provider installation process

  1. Collect the required_providers from the root module and all child modules, and merge the constraints.
  2. 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 -upgrade re-selects the latest version that satisfies the constraint.
  3. Service discovery: GET https://registry.terraform.io/.well-known/terraform.json gets the providers.v1 path; GET /v1/providers/kreuzwerker/docker/versions list versions and platforms.
  4. GET /v1/providers/kreuzwerker/docker/4.7.0/download/linux/amd64 returns the zip download URL,SHA256SUMS , its GPG signature, and the signing public key.
  5. 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/.
  6. Write or update the lock file.

Caching and mirrors

  • Plugin cache: set TF_PLUGIN_CACHE_DIR (or in the CLI configuration file ~/.terraformrc under plugin_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_installation block can specify filesystem_mirror (a local directory, generated with terraform providers mirror ),network_mirror (an HTTPS mirror service), and direct (direct connection to the origin Registry), and use include/exclude to 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 lock to 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

TerraformnpmPython pipGo modules
Range declarationrequired_providers.versionpackage.json ^1.2requirements.ingo.mod
Locked.terraform.lock.hcl (version + multi-platform hashes)package-lock.jsonpip-tools / uv lockgo.sum
Upgradeinit -upgradenpm updatepip-compile -Ugo get -u
Common misconceptions① “~> 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

required_providers~> 4.7 (all modules merged) .terraform.lock.hclLocked 4.7.0 + hashes Version selectionLocked and satisfies the constraint → use the lock-upgrade → choose the latest match Cache TF_PLUGIN_CACHE_DIRHit and hash matches → reuse Mirror provider_installationfilesystem / network mirror registry.terraform.ioversions → download → SHA256SUMS+sig VerifyGPG signature · zip SHA-256Compare with lock file h1/zh .terraform/providers/…/4.7.0/linux_amd64/ Failure example: hash mismatch → “doesn't match any of the checksums”
Figure 3-1: version selection gives priority to the lock file; the installation source is determined by the CLI configuration; packages from any source must pass hash verification

Multi-platform locks: why a lock file generated on macOS may fail on Linux CI

Developer Mac (darwin_arm64) terraform inith1: darwin_arm64 onlyzh: all platforms (from SHA256SUMS) Linux CI (linux_amd64) Extracted package obtained from cache/mirrorCan only compute h1 → no linux h1 in the lock file→ verification fails or reports that the lock file is incomplete Fix terraform providers lock \-platform=linux_amd64 \-platform=darwin_arm64 \-platform=windows_amd64→ every platform has an h1; commit the lock file
Figure 3-2: when downloading the zip directly from the Registry, zh can be used for verification; when using an extracted package from cache or a filesystem mirror, h1 is required

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.

After changing the constraint or the lock file, click init.
$ terraform init

Provider-related commands

CommandPurposeKey options / notes
terraform initInstall 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 providersShows the providers and constraints each module requires, as a treeFind out “who requires this provider”
terraform providers lockCompute and write hashes for the specified platforms-platform=linux_amd64 can be repeated; -fs-mirror/-net-mirror
terraform providers mirror DIRDownload the providers needed by the current configuration into a directory, for use by filesystem_mirror-platform=…
terraform versionShow the selected provider versionsrequires 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)

View the current lock (in the project from Module 2):
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.0
Experience “the lock file takes priority”: relax the constraint to version = ">= 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.

Experience “constraint vs. lock conflict”: change the constraint to 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.

Restore and complete the multi-platform hashes:
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
CI simulation: use read-only lock file mode to confirm that the lock file does not need to change:
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).

Command-line tasks
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
Scenario analysis
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

▶
HashiCorp Terraform Associate Certification Course (003) - Pass the Exam! — freeCodeCamp.org
English · a long certification course; the provider, version constraint, and lock file chapters can extend this module

No short, verified video specifically explaining dependency lock files was found; follow the official documentation and the storyboard below.

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–80s
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.
or reach ≥ 70% on the quiz

Module 4 · Resources, Dependencies, and Lifecycle

19:00 – 27:00 · References create dependencies; dependencies determine order; lifecycle changes “how to replace, whether something can be deleted, and which changes to ignore”
8 minreplace_triggered_by (1.2+) · -replace (0.15.2+)★★★★★
Learning objectives
  • 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, and precondition/postcondition.
  • Use terraform apply -replace=ADDR to force replacement of a single resource (replacing the deprecated terraform taint), and use count to create multiple instances.
Prerequisites: The dependency graph and project from Modules 1–2. Importance:★★★★★ (one of the most common sources of production incidents: accidental replacement and deletion)

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 name redis and the configuration contains only the string REDIS_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

SymbolActionWhen it happens
+createIn the configuration, not in state
~update in-placeAttribute 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
-destroythe 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

ArgumentEffectTypical useNote
create_before_destroy = trueCreate the new object first, then delete the old one during replacementReduce 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 = trueAny plan that would delete the resource fails with an errorData volumes, databases, state storage bucketsVariables cannot be used; removing the entire resource block also removes the protection
ignore_changes = [attr, …] or allIgnore changes to these attributes when computing the diffAttributes 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 replacedDownstream 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 / postconditionChecks conditions at plan/apply time and errors if they failAssumption 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 taint Deprecated.
  • count = 2: create docker_container.app[0],app[1], and inside a block use count.index; with map or set keys, for_each is 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.name as REDIS_HOST gives you the dependency automatically); only write depends_on when a reference truly isn't possible.
  • Stateful data (volumes, databases, storage accounts) should always get prevent_destroy, together with backups.
  • ignore_changes is “acknowledging that others also manage it”; state who and why in a comment.

Comparison with similar technologies

TerraformDocker ComposeKubernetesCloudFormation
DependenciesReference (implicit) + depends_ondepends_on (can carry condition: service_healthy)No startup order; relies on probes and retriesRef/GetAtt + DependsOn
Replacement strategyDelete then create by default; create_before_destroy is optionalRecreate the containerRolling update (maxSurge)“Replacement” defaults to create then delete
Deletion protectionprevent_destroyNoneFinalizers / external policyDeletionPolicy: Retain, termination protection
Common misconceptions① “The more depends_on the safer”—unnecessary depends_on lowers parallelism, and using depends_on on a data source defers its read until apply, causing many “known after apply” values in the plan. ② “depends_on guarantees the app is available”—it only guarantees that the object is created at the Docker/cloud API level; it does not guarantee that the Redis process is ready to accept connections (that is the job of health checks and retries). ③ “prevent_destroy prevents all accidental deletion”—it cannot stop deleting the entire resource block, or someone deleting it in the console. ④ “After ignore_changes, the attribute is no longer in state”—state still records the real value; it is only ignored in the diff.

Replacement strategy: delete then create vs. create then delete

Default -/+ (destroy → create) Old app-0 running Delete old app-0 Gap period: no app-0(downtime) Create new app-0 The name can be reusedHas downtime create_before_destroy +/- Old app-0 running Create new object(old and new coexist) Downstream switches to the new object Delete the old object Unique attributes must differ(add a random suffix to the name) Fixed name = "myapp-dev-app-0" + create_before_destroy → Docker returns Conflict: name already in use
Figure 4-1: create_before_destroy eliminates the gap period, but only if the old and new objects can exist at the same time

Stack in this lesson: which are implicit dependencies and which need depends_on

docker_network.app data.docker_image.myapp docker_container.redis docker_container.app[0..1] docker_container.nginx network.id .id depends_on (only the "REDIS_HOST=redis" string) c.name (template) replace_triggered_by Solid line: implicit (reference) Dashed line: explicit depends_on Dotted line: replacement linkage
Figure 4-2: reference whenever you can; string conventions (DNS names) are invisible to Terraform

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.

Not created / no changeIn progressDoneNew objectDeleted / failed

Commands and arguments

CommandPurposeNotes
terraform apply -replace=ADDRForce replacement of a resource instanceCan be repeated; quote the address when it contains square brackets
terraform plan -target=ADDRPlan only a particular resource and its dependenciesFor emergencies only; Terraform will warn you; do not use as a daily workflow
terraform apply -parallelism=NAdjust parallelismDefault 10
terraform state listList resource addresses in stateModule 7
terraform showShow 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)

app.tf: two myapp containers (reads the locally built image, and explicitly depends on redis)
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]
}
EOF
nginx.tf: reverse proxy, configuration generated from a heredoc template
cat > 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]
  }
}
EOF
Protect the Redis data volume: edit network.tf, and in docker_volume.redis_data add:
resource "docker_volume" "redis_data" {
  name = "${local.name_prefix}-redis-data"

  lifecycle {
    prevent_destroy = true
  }
}
Run plan and apply, and observe the batched parallel execution
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.
Verify load balancing and the counter
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 minutes
Forced replacement + replacement linkage:
terraform 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.

prevent_destroy in effect:
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.

(Exercise) create_before_destroy and the name conflict: add 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.

Command-line tasks
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'
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! — DevOps Directive
English · chapters on resources, dependencies, and meta-arguments (count, depends_on, lifecycle)

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–90s
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.
or reach ≥ 70% on the quiz

Module 5 · Variables, Outputs, Locals

27:00 – 34:00 · a variable is a function parameter, an output is a return value, and a local is a local variable inside the function
7 minvalidation referencing other variables (1.9+) · ephemeral variables (1.10+)★★★★★
Learning objectives
  • Declare accurate type constraints (including object and optional()), 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 output to expose results, use locals to eliminate repetition, and know the boundaries of all three.
Prerequisites: The block syntax from Module 2. Importance:★★★★★

What: the roles of the three kinds of “values”

variable (input variable)locals (local values)output (output values)
AnalogyFunction parametersLocal variables inside a functionFunction return values
Who assignsThe caller (CLI, tfvars, environment variables, parent module)The module author; expressions are evaluatedThe module author
Can use expressions?Defaults must be literals (cannot reference other values)Can reference any valueCan reference any value
Referenced byvar.NAMElocal.NAMEthe parent module's module.M.NAME; the CLI terraform output NAME
Written to state?No (only values used by resources)NoYes (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
}
TypeExampleNotes
string / number / bool"dev" / 8080 / truePrimitive 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)

  1. In the variable declaration's default
  2. Environment variables TF_VAR_name (for example, export TF_VAR_http_port=8081)
  3. terraform.tfvars (loaded automatically)
  4. terraform.tfvars.json (loaded automatically)
  5. *.auto.tfvars / *.auto.tfvars.json (loaded automatically, in filename alphabetical order)
  6. 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 NAME or -json can 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 description and a precise type; where validation is possible, add a validation to 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

TerraformBicepAnsibleHelm
Inputvariable + tfvarsparam + .bicepparaminventory vars / extra-vars (22 levels of precedence)values.yaml + --set
Validationtype + validationdecorators @minValue, @allowedargument_spec / assertvalues.schema.json
Sensitivesensitive (still plaintext in state), ephemeral@secure()Vault / no_logNo built-in
Common misconceptions① “A variable's default can reference other variables”—no, defaults must be literals; use locals for derived values. ② “After sensitive = true, the state is safe”—state still holds plaintext; you must protect the state itself. ③ “terraform.tfvars has the highest precedence”—command line -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

1 · default 2 · TF_VAR_name 3 · terraform.tfvars(.json) 4 · *.auto.tfvars (alphabetical) 5 · -var / -var-file (later wins) Final valuevar.http_port The higher up and to the right, the higher the precedence; within the same level, later-loaded values override earlier-loaded ones
Figure 5-1 mnemonic: default → environment → file → auto file → command line

Data flow: variable → locals → resource → output

variablesproject = "myapp"env = "dev"app_replicas = 2http_port = 8080 localsname_prefix ="${project}-${env}"common_labels = {…} resourcesapp[count = 2]nginx ports.externalrandom_password.app outputsurlapp_containersapp_secret(sensitive) var can also be used directly by resources
Figure 5-2: locals sit in the middle layer; only outputs are written to state and visible externally

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.

variable "http_port" { type = number default = 8080 validation { condition = var.http_port > 1024 } }

Commands and arguments

Command / argumentPurposeNotes
-var 'name=value'Assign on the command lineFor complex types, use HCL syntax: -var 'tags={a="1"}'
-var-file=prod.tfvarsLoad an extra variable fileCan be repeated; later files override earlier ones
-input=falseDisable interactive promptsRequired in CI
TF_VAR_nameAssign via environment variablesSuitable 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)

Expand variables.tf (overwrite the whole file):
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
Use the variables and add a randomly generated secret:
# 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).

plan: observe sensitive and replacement
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.

Experience precedence:
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 replacement
validation blocks bad input:
terraform 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.
Trap with prod tfvars (plan only, do not apply):
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.

sensitive is not encryption:
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.

Command-line tasks
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"
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! — DevOps Directive
English · Variables and Outputs chapter
▶
HashiCorp Terraform Associate Certification Course - Pass the Exam! — freeCodeCamp.org
English · certification course (older exam outline); the variables and outputs sections still apply

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–80s
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.
or reach ≥ 70% on the quiz

Module 6 · Data Sources and Expression Functions

34:00 – 41:00 · data is read-only; functions, for expressions, and dynamic blocks let configuration “compute” values rather than “copy” them
7 minprovider functions (1.8+)★★★★☆
Learning objectives
  • 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 for expressions (including if filtering and grouping ...), splat [*], conditional expressions, and dynamic blocks.
  • Use terraform console to interactively debug expressions.
Prerequisites: Modules 2 and 5. Importance:★★★★☆

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
}
resourcedata
LifecycleCreate / update / deleteRead-only; re-read on every plan
stateRecords the ID and attributesResults are also recorded in state (for reference), but there is no “destroy”
Addressdocker_image.nginxdata.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

CategoryFunctionsExample → result
Stringsformat join split upper lower replace trimspace substr startswithjoin(",", ["a","b"]) → "a,b"
Collectionslength concat merge flatten distinct keys values lookup contains zipmap element slice rangemerge({a=1},{b=2}) → {a=1,b=2}
Type conversiontostring tonumber tolist toset tomaptoset(["a","a"]) → ["a"]
Encodingjsonencode jsondecode yamlencode yamldecode base64encode urlencodejsonencode({a=1}) → "{\"a\":1}"
Files and templatesfile templatefile fileexists filesha256 filesettemplatefile("x.tftpl", {n=2})
Networkcidrsubnet cidrhost cidrnetmaskcidrsubnet("10.20.0.0/16", 8, 1) → "10.20.1.0/24"
Hash / random identifierssha256 md5 uuid timestampuuid(),timestamp() change on every evaluation; avoid using them for resource arguments
Error handlingtry can coalesce onetry(var.cfg.port, 80)
Sensitivitysensitive nonsensitiveManual marking / unmarking
Provider functionsBuilt-in terraform provider: provider::terraform::encode_tfvars,decode_tfvars,encode_exprthe 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

TerraformBicepCloudFormationPulumi
Read existing resourcesdata blockexisting keywordArguments + SSM dynamic references / imported valuesget* Functions
Loop generationfor,dynamic,count/for_eachfor LoopsFn::ForEach (language extension)Native to the language
TemplatestemplatefileloadTextContent + string functionsFn::SubNative to the language
Common misconceptions① “A data source is only read on the first plan”—it is read on every plan/apply (unless you use -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

Case A: all arguments known (literal "nginx:alpine") plan: ReadDataSource→ registry lookup for the digest digest knownpull_triggers can be compared Exact plan: No changes or“docker_image.nginx must be replaced” Case B: an argument references a value that is known after apply, or depends_on has changes plan: cannot be read<= read (data resources) All attributes unknownpropagate to downstream Downstream shows known after applyForceNew attribute → may be replaced at apply timeReadDataSource Keep data sources depending only on known values, so the plan is exact
Figure 6-1: the earlier a data source is read, the more trustworthy the plan

How a for expression is evaluated

docker_container.app (list)[0] name=myapp-dev-app-0 ip=10.20.0.3[1] name=myapp-dev-app-1 ip=10.20.0.4 { for c in docker_container.app :c.name => c.network_data[0].ip_address }bind each c in turn → compute the key and value Result (map)"myapp-dev-app-0" = "10.20.0.3""myapp-dev-app-1" = "10.20.0.4"Duplicate keys cause an error (unless ... is used)
Figure 6-2: square brackets produce a list (tuple), curly braces produce a map (object)

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 .

Input data
Result
>

terraform console Related commands

CommandPurposeNotes
terraform consoleInteractive evaluation (can reference var, local, resources, data)Reads the current state; exit or press Ctrl+D to exit
echo 'EXPR' | terraform consoleNon-interactive evaluationSuitable for scripts and quizzes
terraform console -var 'x=1'Start with variablesSame variable arguments as plan
terraform metadata functions -jsonList all available functions and their signaturesRequires 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)

Make the nginx image follow the registry's digest: edit 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.

Refactor the heredoc into a template file:
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.

for expression output: container name → IP: in 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"
}
Scale to 3 replicas and observe the template and outputs follow automatically:
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.

console exercise: use 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 console

Case 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... }.

Command-line tasks
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]
Scenario analysis
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

▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · chapters on data sources and functions

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–80s
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.
or reach ≥ 70% on the quiz

Module 7 · State Basics

41:00 – 50:00 · state is Terraform's “memory”: a mapping from configuration addresses to real objects; it may contain secrets, must be protected, and must not be edited by hand
9 minstate format version 41.17: -minimal-refresh★★★★★
Learning objectives
  • 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 use plan/apply -refresh-only to identify and handle drift.
Prerequisites: The apply mechanics from Module 1. Importance:★★★★★ (state problems are the number one source of Terraform production incidents)

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 ID a41f…. 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
}
FieldMeaning
versionState file format version (currently 4)
serialIncremented each time the state content changes; remote backends use it to prevent an old state from overwriting a new one
lineageA UUID generated when the state is first created; states with different lineages cannot overwrite each other (prevents pushing dev state to prod)
modemanaged (resource) or data (data source)
index_keyThe numeric index for count or the string key for for_each
sensitive_attributesWhich 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=false or, in 1.17, -minimal-refresh to 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.

CommandWhat it doesWrites state?Changes the real world?
terraform planrefresh (in memory) + compute diffNoNo
terraform plan -refresh-onlyOnly shows driftNoNo
terraform apply -refresh-onlyWrites drift into state (“accept reality”)YesNo
terraform applyConverges the real world to the configuration (“fix drift”)YesYes
terraform refreshDeprecated, equivalent to apply -refresh-only -auto-approve (no confirmation, dangerous)YesNo
plan -refresh=falseSkips refresh and computes from state directly (fast, but may be based on stale information)NoNo
plan -minimal-refresh (1.17)Only refreshes resources with proposed changesNoNo

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 a moved block, to change the address),terraform state rm (or a removed block, to stop managing without deleting the object),import block (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

TerraformCloudFormationBicep / ARMPulumiAnsible
State storagetfstate (you manage storage)AWS-managed stackNone (deployment history; Deployment Stacks track managed resources)Pulumi Cloud / self-managed backendNone
Drift detectionplan / plan -refresh-onlyDrift detection (console/API)what-ifpulumi refresh / preview--check --diff
SecretsState in plaintext (must be protected)AWS-managed@secure not recordedEncrypts secrets by defaultVault
Common misconceptions① “State is just a cache; delete it and it regenerates”—after deletion Terraform assumes nothing exists and tries to recreate all resources (failing on name conflicts, or creating duplicate resources in the cloud). ② “plan updates state”—since 0.15.4 plan does not write state; only apply (including -refresh-only) writes. ③ “Terraform manages all resources in the account”—it only manages objects recorded in state; similar resources created by hand are invisible to it. ④ “Sensitive values in state are encrypted”—no.

Three-way comparison: configuration · state · real world

Configuration *.tf (desired)app_replicas = 2redis.restart = "unless-stopped" state (last recorded)app[0] id=a41f… app[1] id=b72c…redis.restart = "unless-stopped"serial 14 Real world (Docker)app-1 has been removed with docker rmredis restart = "no" (changed)There is another manual container, debug (unmanaged) ① refresh ② diff Plan Note: Objects have changed outside of Terraform (app[1] deleted · redis restart "unless-stopped" → "no") + create app[1] ~ update redis restart "no" → "unless-stopped" (the debug container does not appear)
Figure 7-1: refresh updates the “prior state” with the real world; the diff is then compared with the configuration; objects not in state are invisible to Terraform

When state is written, and backups

apply startsAcquire lock (local file lock) Resource A completesWrite state, serial + 1 Resource B completesWrite state Resource C failsA and B are still in state Release lockExit code 1 A local backend saves the old contents as terraform.tfstate.backup before each write; a remote backend relies on the storage's versioning
Figure 7-2: state is updated resource by resource, so re-running apply after a failure is safe

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.

Create change:
Terraform:

State inspection commands

CommandPurposeNotes
terraform state listList all resource addressesCan be filtered: terraform state list 'docker_container.app',-id=ID
terraform state show ADDRShow the attributes of a single resource in HCL styleSensitive values are displayed as (sensitive value)
terraform showShow the entire state (or a plan file)-json Output in a machine-readable format (includes plaintext sensitive values)
terraform state pullOutput the raw state JSON (also works with remote backends)Backup: terraform state pull > backup.tfstate
terraform plan -refresh-onlyView drift onlyScheduled drift detection in CI
terraform apply -refresh-onlyAccept drift and write it to stateRequires confirmation
terraform state mv / rm,importControlled ways to modify stateLesson 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)

Record the baseline
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
Look at the secrets in state
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.

Create three kinds of “external changes”
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
Drift only: plan -refresh-only
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.

Normal plan: how Terraform plans to fix it
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”.

Experience the “accept reality” trap: apply -refresh-only
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.

Fix the drift
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.

Command-line tasks
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
Scenario analysis
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

▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · covers the role of state and the plan/apply flow
▶
Complete Terraform Course - From BEGINNER to PRO! — DevOps Directive
English · chapter on Terraform state and remote backends (the remote part corresponds to Lesson 2)

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–90s
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.
or reach ≥ 70% on the quiz

Module 8 · CLI Workflow and Troubleshooting Basics

50:00 – 60:00 · init → fmt → validate → plan -out → review → apply plan file; understand exit codes, logs, and the most common errors
10 min-detailed-exitcode · plan file★★★★★
Learning objectives
  • 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_AUTOMATION to write CI scripts.
  • Use TF_LOG to collect logs, and use the interactive troubleshooting tree to locate common errors by “stage”.
Prerequisites: Modules 1–7. Importance:★★★★★

What: the core workflow

StepCommandWhat it checksAccesses the API?Writes state?
1terraform initInstall providers/modules, configure the backend, verify the lock fileRegistry / backendNo (but migrating the backend does)
2terraform fmt -checkfmtNoNo
3terraform validateSyntax, references, types, provider schemaNoNo
4terraform plan -out=tfplanrefresh + diff, generating a plan fileYes (reads)No
5terraform show tfplanHuman/automated review (-json to a policy tool)NoNo
6terraform apply tfplanExecutes strictly per the plan, without asking againYes (writes)Yes
—terraform destroyEquivalent to apply -destroy: plans to delete all managed resourcesYesYes

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.

A plan file contains secrets A plan file (a binary zip) contains variable values and resource attributes, which may include plaintext secrets. Do not commit it to Git; in CI, pass it along as a short-lived artifact and delete it when done.

How: exit codes and automation

CommandExit codeMeaning
plan -detailed-exitcode0 / 1 / 20 = success with no changes; 1 = error; 2 = success with changes
Other commands0 / 1Success / failure
fmt -check0 / 3 (files need formatting)Any non-zero requires handling
  • -input=false (or TF_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, or JSON (JSON format at TRACE level). TF_LOG_CORE,TF_LOG_PROVIDER control core and provider separately. TF_LOG_PATH Written to a file.
  • Generated when Terraform itself panics; crash.log if 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

  1. 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).
  2. 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").
  3. 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).
  4. Turn on logs when necessary: TF_LOG=DEBUG to see the specific requests and responses.

Comparison with similar technologies

TerraformBicep / azCloudFormationPulumi
Previewplanaz deployment group what-ifChange setpulumi preview
Execute as previewedapply tfplan (rejected if stale)No strict bindingExecute the change setpulumi up (can be --plan)
CI drift detection-detailed-exitcodewhat-if parsingDrift detection APIpreview --expect-no-changes
Common misconceptions① “If validate passes, the deployment will work”—validate does not access the API, so port conflicts, permissions, and quotas are not caught. ② “-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

init-lockfile=readonly fmt -checkexit code 0/3 validateoffline checks plan -out=tfplan-detailed-exitcode review / policyshow -json tfplan apply tfplanno longer asks state is changed after plan→ Error: Saved plan is stale → re-plan exit 0: no changes, skip applyexit 2: changes, enter reviewexit 1: failure, block the pipeline The PR stage only goes as far as review; after merging to the main branch, a protected job runs apply (Lesson 5)
Figure 8-1 “what is reviewed is what is executed”: the plan file is the contract between plan and apply

Categorize errors by stage

initprovider not found (hashicorp/docker)No version matches the constraintLock file mismatch / checksumNetwork / proxy validateUnsupported argument / blockReference to undeclared …Incorrect attribute value typeMissing required argument planCycleInvalid for_each / countMissing variable / validationAPI unreachable during refreshprevent_destroy apply (API error)Conflict: name already in useport is already allocatedpermission denied / 403Quota / rate limiting (429)Saved plan is stale
Figure 8-2: the further left the error, the cheaper it is; catch it as early as possible in CI

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

CommandCommon optionsNotes
terraform init-upgrade -lockfile=readonly -backend=false -reconfigureRun after any fresh clone, or after changing the provider/module/backend
terraform fmt-check -diff -recursiveFormat
terraform validate-jsonRequires 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 showFILE -json -no-colorView a plan or state
terraform applyFILE -auto-approve -refresh-only -replace -lock-timeoutCannot 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 -rawModule 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)

Write a CI-style script
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
Produce changes and save the plan
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.
Create an “expired plan”: during the “review period”, another person runs an apply:
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.

apply the plan file
./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
Create and locate an error in the apply stage:
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.

Preview destruction (without executing): 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.

Command-line tasks
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'
Scenario analysis
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

▶
HashiCorp Terraform Associate Certification Course (003) - Pass the Exam! — freeCodeCamp.org
English · chapter on the Terraform CLI workflow (init/plan/apply/destroy)
▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · command demonstration with labs

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video or MP3, so the storyboard and narration script are provided.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–90s
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.
or reach ≥ 70% on the quiz

Command cheat sheet

Terraform 1.17 · kreuzwerker/docker 4.7 · every code block can be copied with one click
After-class reference

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.svg

Variables 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 / errorStageMost likely causeFirst diagnostic commandModule
does not have a provider named registry.terraform.io/hashicorp/dockerinitModule not declared source = "kreuzwerker/docker"terraform providersM3
locked provider … does not match configured version constraintinitConstraint changed but lock not upgradedterraform init -upgradeM3
doesn't match any of the checksums previously recordedinitLock file lacks h1 for the current platformterraform providers lock -platform=…M3
Unsupported argument / Did you mean to define a blockvalidateNested block was written as = {}terraform providers schema -jsonM2
Reference to undeclared resourcevalidateTypo / subdirectory not loadedgrep -n 'resource "' *.tfM2
Cycle: …planMutual referencesterraform graph -type=planM4
Invalid value for variableplanValidation failedCheck tfvars / -varM5
Instance cannot be destroyedplanprevent_destroyterraform plan See which resource will be deletedM4
Error pinging Docker server / permission denied … docker.sockplan/applyDocker not running / not in docker groupdocker info,id -nGM1
Conflict. The container name … is already in useapplyUnmanaged object with the same name / CBD + fixed namedocker ps -a --filter name=…M1/M4
port is already allocatedapplyHost port in usess -ltnpM8
Saved plan is staleapplyState modified after planRe- plan -outM8
all resources want createplanState lost / wrong directoryls terraform.tfstate*, do not applyM7

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

Use Terraform to manage the complete local myapp stack from scratch (nginx + 2 × myapp + redis + network + volume), demonstrating drift detection and repair
≈ 25 minZero cloud cost
Scenario

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.

Clean up the lab stack (release names, ports, and subnets)
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.

Create a new root module ~/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
ls
init, lock three platforms, static checks
terraform init
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
terraform fmt -check -recursive && terraform validate
plan → review → apply
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.

Verify
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
Drift A: drift that Terraform can see
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).

Drift B: drift that Terraform cannot see— someone went into the container and changed the nginx configuration:
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
Change rehearsal and protection verification
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
Cleanup (to keep the data volume, skip the first sed line and use 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.

Acceptance checklist

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

Basis for verifying all technical facts in this lesson (verified 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
Terraform CLI versionLatest 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.7releases.hashicorp.com/terraform · v1.17 CHANGELOG
New features in 1.17provider 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_versionv1.17 CHANGELOG
Installation methodHashiCorp apt repository command (keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg, UBUNTU_CODENAME detected automatically); the page shows the latest version 1.17.2Install Terraform
kreuzwerker/dockerLatest 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 imagesRegistry · CHANGELOG
hashicorp/random, localrandom 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.9Registry / OpenTofu releases (verified by the course coordinator, 2026-11)
Plugin architectureProviders are separate processes that communicate over gRPC (plugin protocol v5/v6); RPCs: GetProviderSchema, Validate*Config, ConfigureProvider, UpgradeResourceState, ReadResource, ReadDataSource, PlanResourceChange, ApplyResourceChange, ImportResourceStatePlugin Protocol · How Terraform Works
Lock file and provider installationh1/zh hashes,providers lock -platform, plugin cache and provider_installationDependency Lock File · CLI Config
Languagevariable precedence, types, validation, lifecycle, for expressions, functionsTerraform Language
State and driftstate structure, sensitive data, refresh-onlyState · Resource Drift
CLI and automation-detailed-exitcode (0/1/2), plan files, TF_LOG, TF_IN_AUTOMATIONplan · 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_container have dozens of computed attributes) are heavily abbreviated in the examples.
  • The conclusion of “drift B” (upload content 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_image so data sources may hit 429 when plan is run frequently.