Day 3: Understanding State
Goal: Know what’s in the state and why it matters, read dependencies, detect changes from the outside (drift), and replace individual resources on purpose. · Duration: approx. 75 min · Prerequisite: Day 2
Briefing
- The state (
terraform.tfstate) is OpenTofu’s memory: it connects every resource in the code with a real object (via its ID) and records the last known values. - On every
plan, OpenTofu reads the real status again (refresh) and compares three ways: code, state, reality. - Drift means: someone changed something outside of
OpenTofu. The plan shows it;
-refresh-onlytakes reality into the state without changing anything. - The state contains all attributes – passwords too. It is never edited by hand and never checked into Git.
Code (*.tf) ─┐
State ───────┼─► tofu plan ─► differences ─► apply
Reality ─────┘ (refresh) └ drift: "has been deleted / changed outside"
Drill 1: What’s in the State
mkdir -p ~/tf-lab/tag03 && cd ~/tf-lab/tag03
cat > main.tf <<'EOF'
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 4.6"
}
}
}
provider "docker" {}
resource "docker_network" "notes" {
name = "notes-tag03"
}
resource "docker_volume" "db" {
name = "notes-db-tag03"
}
resource "docker_image" "postgres" {
name = "postgres:18.6-alpine"
keep_locally = true
}
resource "docker_container" "db" {
name = "notes-db-tag03"
image = docker_image.postgres.image_id
env = [
"POSTGRES_USER=notes",
"POSTGRES_PASSWORD=lab-db-pw-123",
"POSTGRES_DB=notes",
]
networks_advanced {
name = docker_network.notes.id
}
volumes {
volume_name = docker_volume.db.name
container_path = "/var/lib/postgresql"
}
}
EOF
tofu init -no-color >/dev/null
tofu apply -auto-approve -no-color | grep 'Apply complete'
tofu state list
tofu state show docker_container.db | grep -E '^ (name|hostname|restart) +='
jq -c '{version, serial, lineage: .lineage[0:8]}' terraform.tfstate
grep -c 'lab-db-pw-123' terraform.tfstateExpected:
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
docker_container.db
docker_image.postgres
docker_network.notes
docker_volume.db
hostname = "9e78154a87ae"
name = "notes-db-tag03"
restart = "no"
{"version":4,"serial":1,"lineage":"dd1ff8d3"}
1
- The state is JSON.
serialcounts up with every change to the state,lineageidentifies exactly this state – OpenTofu refuses to overwrite a state with a differentlineage. - The database password is in it in plain text. Anyone who can read the state knows all the secrets of this configuration (Days 9 and 12).
tofu state showshows a resource the way OpenTofu last saw it – including values you never set, like thehostname.
Save your progress? Sign up for free
Drill 2: Dependencies
tofu graph | grep -- '->' | grep -v providerExpected (indented):
"[root] docker_container.db (expand)" -> "[root] docker_image.postgres (expand)"
"[root] docker_container.db (expand)" -> "[root] docker_network.notes (expand)"
"[root] docker_container.db (expand)" -> "[root] docker_volume.db (expand)"
Each line is an edge: the container depends on image, network, and
volume. [root] and (expand) are internal
markers of OpenTofu; grep -v provider hides the edges to
the provider.
The graph is built from the references in the code. When creating,
OpenTofu works from the bottom up (first image, network, and volume,
then the container); when deleting, the other way around. If a reference
is missing even though a dependency exists,
depends_on = [ … ] helps.
Save your progress? Sign up for free
Drill 3: Drift
Someone deletes the container by hand:
docker rm -f notes-db-tag03 >/dev/null
tofu plan -no-color | grep -E 'has been deleted|will be created|Plan:'Expected:
# docker_container.db will be created
Plan: 1 to add, 0 to change, 0 to destroy.
The refresh noticed that the container is missing, and the plan creates it again. The volume remained – and so did the data. Sometimes, though, reality should win:
tofu plan -refresh-only -no-color | grep -E 'has been deleted|refresh-only|Objects'
tofu apply -refresh-only -auto-approve -no-color | grep -E 'Apply complete'
tofu state list | grep -c docker_container
tofu apply -auto-approve -no-color | grep 'Apply complete'Expected:
Note: Objects have changed outside of OpenTofu
# docker_container.db has been deleted
This is a refresh-only plan, so OpenTofu will not take any actions to undo
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
0
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
apply -refresh-only only rewrites the state: the
container is now gone there too. The next normal apply
creates it again because the code requires it.
Save your progress? Sign up for free
Drill 4: Targeted Replacement
docker ps -q --filter name=notes-db-tag03
tofu apply -replace=docker_container.db -auto-approve -no-color | grep 'Apply'
docker ps -q --filter name=notes-db-tag03
tofu plan -target=docker_volume.db -no-color 2>&1 | grep -E 'targeting|Plan:|No changes'Expected (the IDs differ – what matters is that they are different from each other):
3f2a9c1b7d4e
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
8c0d5e6f1a2b
No changes. Your infrastructure matches the configuration.
Warning: Resource targeting is in effect
-replace=adresseforces recreation – for example when a container hangs even though its configuration is correct.-target=adresselimits plan and apply to one resource and its dependencies. OpenTofu warns explicitly: this is a stopgap, not everyday practice.
Save your progress? Sign up for free
Drill 5: Backups and Reading the State
ls terraform.tfstate*
tofu show -json | jq '.values.root_module.resources[].address'
tofu state pull | jq '.serial'Expected (the number depends on your runs):
terraform.tfstate
terraform.tfstate.backup
"docker_container.db"
"docker_image.postgres"
"docker_network.notes"
"docker_volume.db"
4
- Before every write, OpenTofu backs up the old state as
terraform.tfstate.backup– exactly one generation. tofu show -jsonandtofu state pullare the official ways to read the state. Reading the file directly works too, but only as long as the state is local.
Save your progress? Sign up for free
Checkpoint
tofu state list | wc -lExpected:
4
tofu plan -detailed-exitcode -no-color >/dev/null; echo "Exit: $?"Expected:
Exit: 0
cat .gitignore 2>/dev/null || echo "noch keine .gitignore"Expected:
noch keine .gitignore
Challenge
Create a .gitignore that prevents state, backups, and
the .terraform folder from getting into Git – but lets the
lock file in. Check it with git status in a fresh
repository.
Hint: git init -q and
git status --short --ignored.
Solution
cat > .gitignore <<'EOF'
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
crash.log
EOF
git init -q && git status --short | sortExpected:
?? .gitignore
?? .terraform.lock.hcl
?? main.tf
*.tfvars is a precaution: passwords tend to end up
there. Variable values without secrets may still go into Git – then with
their own name like dev.auto.tfvars and an exception
!dev.auto.tfvars.
Save your progress? Sign up for free
Enterprise Note
- State doesn’t belong on a laptop: In a team it is stored centrally, encrypted, and with a lock against concurrent runs (Day 9).
- State size: A configuration with thousands of resources makes every plan slow and every mistake expensive. Small, separate states (per service, per environment) are easier to manage.
- Look for drift regularly: A scheduled
tofu plan -detailed-exitcodereports exit code 2 as soon as someone has changed something by hand (Day 14).