Skip to content
Hands-on IT IT Drills

Day 1: First Resources with the Docker Provider

Goal: Write a first configuration, go through the lifecycle with init, plan, apply, and destroy, and learn to read what OpenTofu intends to do – above all, when it replaces something instead of changing it. · Duration: approx. 60 min · Prerequisite: Day 0

Briefing

  • A configuration consists of .tf files in a directory. They contain blocks: terraform (versions), provider (connection), resource (what should exist).
  • tofu init downloads the providers and writes their exact versions to the lock file .terraform.lock.hcl.
  • tofu plan compares desired and actual state and shows the changes: + create, ~ update, -/+ replace, - delete. tofu apply carries them out.
  • Some properties can’t be changed, only recreated. For a container that’s almost all of them – the plan says so with # forces replacement.
 main.tf ─► tofu init  ─► .terraform/ + .terraform.lock.hcl
         ─► tofu plan  ─► "1 to add, 0 to change, 0 to destroy"
         ─► tofu apply ─► Docker: network, image, container  ─► terraform.tfstate

Drill 1: The First Configuration

mkdir -p ~/tf-lab/tag01 && cd ~/tf-lab/tag01
cat > main.tf <<'EOF'
terraform {
  required_version = ">= 1.13.0"
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.6"
    }
  }
}

provider "docker" {}

resource "docker_network" "notes" {
  name = "notes-tag01"
}

resource "docker_image" "postgres" {
  name         = "postgres:18.6-alpine"
  keep_locally = true
}

resource "docker_container" "db" {
  name  = "notes-db-tag01"
  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.name
  }
}
EOF
tofu init -no-color | grep -E 'Installing|Installed|initialized'
ls -A
grep -A2 'provider "registry.opentofu.org/kreuzwerker/docker"' .terraform.lock.hcl

Expected:

- Installing kreuzwerker/docker v4.6.0...
- Installed kreuzwerker/docker v4.6.0 (signed, key ID 0DCE698927DAF8EC)
OpenTofu has been successfully initialized!
.terraform
.terraform.lock.hcl
main.tf
provider "registry.opentofu.org/kreuzwerker/docker" {
  version     = "4.6.0"
  constraints = "~> 4.6"
  • ~> 4.6 allows 4.6, 4.7 … but not 5.0. Which version it actually became is recorded in the lock file – it belongs in Git so everyone uses the same one.
  • docker_image.postgres.image_id is a reference: the container needs the image, so OpenTofu creates it first.
  • provider "docker" {} without settings uses the local Docker socket.

Terraform: Terraform downloads providers from registry.terraform.io, OpenTofu from registry.opentofu.org. The addresses in the lock file differ; the providers themselves are the same.

Save your progress? Sign up for free

Drill 2: The Plan

tofu plan -no-color | grep -E '^  [#+~-]|Plan:'

Expected:

  + create
  # docker_container.db will be created
  + resource "docker_container" "db" {
  # docker_image.postgres will be created
  + resource "docker_image" "postgres" {
  # docker_network.notes will be created
  + resource "docker_network" "notes" {
Plan: 3 to add, 0 to change, 0 to destroy.

The full plan shows every attribute. Many say (known after apply): the container’s ID, its IP – values that only Docker assigns. The plan changes nothing. It’s the most important thing OpenTofu tells you: Read it every time.

Save your progress? Sign up for free

Drill 3: apply

tofu apply -auto-approve -no-color | grep -E 'Creation complete|Apply complete'
docker ps --filter name=notes-db-tag01
tofu state list

Expected (IDs and times differ):

docker_network.notes: Creation complete after 0s [id=4c1f…]
docker_image.postgres: Creation complete after 0s [id=sha256:10a5c69a8303…]
docker_container.db: Creation complete after 1s [id=9b2e…]
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS  ...
9b2e0c1d4a5f   10a5c69a8303   "docker-entrypoint.s…"   2 seconds ago   Up 1 second ...
docker_container.db
docker_image.postgres
docker_network.notes

Network and image are created at the same time, the container afterwards – OpenTofu builds a dependency graph from the references. -auto-approve skips the confirmation prompt; in day-to-day work you type yes after reading the plan. What was created is stored in the state; tofu state list shows the addresses.

Save your progress? Sign up for free

Drill 4: Update or Replace?

First a different password for the database:

sed -i 's/lab-db-pw-123/lab-db-pw-456/' main.tf
tofu plan -no-color | grep -E 'must be replaced|forces replacement|Plan:'
sed -i 's/lab-db-pw-456/lab-db-pw-123/' main.tf

Expected:

  # docker_container.db must be replaced
      ~ env                                         = [ # forces replacement
Plan: 1 to add, 0 to change, 1 to destroy.

An environment variable can’t be changed in a running container: OpenTofu deletes it and creates it again (-/+). For a database without a volume, the data would be gone – a plan with “to destroy” always deserves a second look.

Now the network gets a label. sed … r datei inserts the contents of a file after the matching line:

cat > label.txt <<'EOF'
  labels {
    label = "kurs"
    value = "tofu"
  }
EOF
sed -i '/^  name = "notes-tag01"$/r label.txt' main.tf
tofu plan -no-color | grep -E 'must be replaced|forces replacement|Plan:'
tofu apply -auto-approve -no-color 2>&1 | grep -E '^Error|Apply complete'

Expected (after about 30 seconds):

  # docker_network.notes must be replaced
      + labels { # forces replacement
Plan: 1 to add, 0 to change, 1 to destroy.
Error: timeout while waiting for state to become 'removed' (last state: 'pending', ti…

The network is supposed to be replaced, but the container isn’t. Docker refuses to delete a network that still has a container attached. Why didn’t OpenTofu replace the container as well? It refers to the network’s name with docker_network.notes.name – and that stays the same. So for OpenTofu, nothing changes about the container. If it refers to the ID, which changes on replacement, OpenTofu recognizes the dependency correctly:

sed -i 's/name = docker_network.notes.name/name = docker_network.notes.id/' main.tf
tofu plan -no-color | grep -E 'must be replaced|Plan:'
tofu apply -auto-approve -no-color | grep 'Apply complete'

Expected:

  # docker_container.db must be replaced
  # docker_network.notes must be replaced
Plan: 2 to add, 0 to change, 2 to destroy.
Apply complete! Resources: 2 added, 0 changed, 2 destroyed.

Remember: references to values that change on replacement (IDs) carry dependencies along. References to values that stay the same (names) don’t.

Save your progress? Sign up for free

Drill 5: destroy

tofu destroy -auto-approve -no-color | grep -E 'Destroy complete'
docker ps -a --filter name=notes-db-tag01 --format '{{.Names}}' | wc -l
docker images postgres:18.6-alpine --format '{{.Repository}}:{{.Tag}}'
tofu state list | wc -l

Expected:

Destroy complete! Resources: 3 destroyed.
0
postgres:18.6-alpine
0

destroy removes everything that’s in the state – and only that. The image stays because keep_locally = true says: when deleting the resource, don’t remove the image from Docker.

Save your progress? Sign up for free

Checkpoint

tofu validate -no-color

Expected:

Success! The configuration is valid.
tofu plan -no-color | grep 'Plan:'

Expected: everything to be created again.

Plan: 3 to add, 0 to change, 0 to destroy.
grep -c 'version     = "4.6.0"' .terraform.lock.hcl

Expected:

1

Challenge

Add a container notes-web-tag01 from the image nginx:1.31.8-alpine that answers on 127.0.0.1:8081. Create everything, check with curl, and clean up again.

Hint: The ports block has internal, external, and ip.

Solution

cat >> main.tf <<'EOF'

resource "docker_image" "nginx" {
  name         = "nginx:1.31.8-alpine"
  keep_locally = true
}

resource "docker_container" "web" {
  name  = "notes-web-tag01"
  image = docker_image.nginx.image_id
  ports {
    internal = 80
    external = 8081
    ip       = "127.0.0.1"
  }
}
EOF
tofu apply -auto-approve -no-color | grep 'Apply complete'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8081/
tofu destroy -auto-approve -no-color | grep 'Destroy complete'

Expected:

Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
200
Destroy complete! Resources: 5 destroyed.

Save your progress? Sign up for free

Enterprise Note

  • Save the plan: tofu plan -out=plan.bin followed by tofu apply plan.bin carries out exactly what was reviewed – even if something changed in the meantime. In CI this is mandatory (Day 14).
  • -auto-approve only in automation, never by hand on production.
  • Spot replacements: lifecycle { prevent_destroy = true } makes every plan fail that would delete an important resource – a seat belt for databases and storage.