Skip to content
Hands-on IT IT Drills

Appendix B: Final Exam

Goal: Show without instructions that you can run infrastructure with OpenTofu as a team: a new environment, a new module version with a test, an import, a secret without state, and a custom policy. · Duration: approx. 90 min · Prerequisite: Day 15

Rules of Play

  • Each exercise only describes the goal. You find the way yourself; the days in parentheses help you look things up.
  • Each exercise ends with a check block: individual commands with what they must show. Only when all of them match does the exercise count.
  • Everything is created under ~/tf-lab/anhb; the state lives in the S3 storage under anhb/….
source ~/tf-lab/setup/env.sh
mkdir -p ~/tf-lab/anhb && cd ~/tf-lab/anhb

Exercise 1: A staging Environment

Create an environment in ~/tf-lab/anhb/staging: module notes-docker in version v1.2.0, name stg, port 8095, one instance a. The state lives under the key anhb/staging.tfstate. (Day 5, Day 9, Day 10)

Check block:

curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8095/healthz

Expected:

200
s3ls 'tofu-state?list-type=2' | grep -o '<Key>anhb[^<]*</Key>'

Expected:

<Key>anhb/staging.tfstate</Key>

Solution

mkdir -p ~/tf-lab/anhb/staging && cd ~/tf-lab/anhb/staging
sed 's|tag05/terraform.tfstate|anhb/staging.tfstate|' ~/tf-lab/tag05/backend.tf \
  > backend.tf
cp ~/tf-lab/tag05/versions.tf .
cat > main.tf <<'EOF'
provider "docker" {}

module "notes" {
  source      = "git::file:///home/ubuntu/tf-lab/module//notes-docker?ref=v1.2.0"
  name        = "stg"
  port        = 8095
  instanzen   = ["a"]
  db_passwort = "lab-db-pw-123"
}
EOF
tofu init -no-color >/dev/null
tofu apply -auto-approve -no-color | tail -1

Expected:

Apply complete! Resources: 9 added, 0 changed, 0 destroyed.

Save your progress? Sign up for free

Exercise 2: Module Version v1.3.0

The module gets an output proxy with the name of the proxy container, and a plan test for it. Release it as v1.3.0 and switch staging over to it. staging exposes the value as its own output proxy. (Day 5, Day 13)

Check block:

git -C ~/tf-lab/module tag --points-at HEAD

Expected:

v1.3.0
cd ~/tf-lab/anhb/staging && tofu output -raw proxy; echo

Expected:

stg-proxy
cd ~/tf-lab/module/notes-docker && tofu test -no-color -filter=tests/plan.tftest.hcl \
  | tail -1

Expected (4 instead of 5 if you didn’t do the challenge from Day 13):

Success! 5 passed, 0 failed.

Solution

cd ~/tf-lab/module/notes-docker
cat >> outputs.tf <<'EOF'

output "proxy" {
  description = "Name des Proxy-Containers"
  value       = docker_container.proxy.name
}
EOF
cat >> tests/plan.tftest.hcl <<'EOF'

run "proxy_name" {
  command = plan

  assert {
    condition     = output.proxy == "test-proxy"
    error_message = "Ausgang proxy stimmt nicht."
  }
}
EOF
tofu test -no-color -filter=tests/plan.tftest.hcl | tail -1
cd .. && git add -A
git -c user.name=Lab -c [email protected] commit -qm "Ausgang proxy"
git tag v1.3.0
cd ~/tf-lab/anhb/staging
sed -i 's/ref=v1.2.0/ref=v1.3.0/' main.tf
cat > outputs.tf <<'EOF'
output "proxy" {
  value = module.notes.proxy
}
EOF
tofu init -no-color >/dev/null
tofu apply -auto-approve -no-color | grep 'Apply complete'

Expected:

Success! 5 passed, 0 failed.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

New module version, no rebuild: the output doesn’t change any resource.

Save your progress? Sign up for free

Exercise 3: The Archive Volume

Someone created a volume stg-archiv by hand. Take it over in staging as the resource docker_volume.archiv – with an import block. (Day 11)

Game master:

docker volume create stg-archiv

Expected:

stg-archiv

Check block:

cd ~/tf-lab/anhb/staging && tofu state list | grep archiv

Expected:

docker_volume.archiv
tofu plan -no-color | tail -1

Expected:

No changes. Your infrastructure matches the configuration.

Solution

cd ~/tf-lab/anhb/staging
cat > archiv.tf <<'EOF'
import {
  to = docker_volume.archiv
  id = "stg-archiv"
}

resource "docker_volume" "archiv" {
  name = "stg-archiv"
}
EOF
tofu apply -auto-approve -no-color | grep 'Apply complete'

Expected:

Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.

Save your progress? Sign up for free

Exercise 4: A Secret Without State

staging gets a Kubernetes Secret stg-api in the namespace anhb with a random 32-character password under the key password. The password must not appear in the state. (Day 6, Day 12)

Check block:

PW=$(kubectl -n anhb get secret stg-api -o jsonpath='{.data.password}' | base64 -d)
echo "${#PW}"

Expected:

32
cd ~/tf-lab/anhb/staging && tofu state pull | grep -c "$PW"

Expected:

0

Solution

cd ~/tf-lab/anhb/staging
cat > versions.tf <<'EOF'
terraform {
  required_version = ">= 1.13.0"
  required_providers {
    docker     = { source = "kreuzwerker/docker", version = "~> 4.6" }
    kubernetes = { source = "hashicorp/kubernetes", version = "~> 3.4" }
    random     = { source = "hashicorp/random", version = "~> 3.9" }
  }
}
EOF
cat > k8s.tf <<'EOF'
provider "kubernetes" {
  config_path = "/etc/rancher/k3s/k3s.yaml"
}

resource "kubernetes_namespace_v1" "anhb" {
  metadata {
    name = "anhb"
  }
}

ephemeral "random_password" "api" {
  length  = 32
  special = false
}

resource "kubernetes_secret_v1" "api" {
  metadata {
    name      = "stg-api"
    namespace = kubernetes_namespace_v1.anhb.metadata[0].name
  }
  data_wo = {
    password = ephemeral.random_password.api.result
  }
  data_wo_revision = 1
}
EOF
tofu init -no-color >/dev/null
tofu apply -auto-approve -no-color | grep 'Apply complete'

Expected:

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

required_providers may appear only once per directory. That’s why all three providers go into versions.tf.

Save your progress? Sign up for free

Exercise 5: A Custom Policy

Add a rule to ~/tf-lab/policy/plan.rego: Docker containers may only publish ports in the range 8000–8999. Check it against a staging plan in which the port is set to 9095. (Day 13)

Check block:

cd ~/tf-lab/anhb/staging && conftest test -p ~/tf-lab/policy neu.json --no-color \
  | grep -o 'Port 9095 nicht in.*'

Expected:

Port 9095 nicht in 8000–8999
grep -c '8095' main.tf

Expected: the port in the code is 8095 again.

1

Solution

cat >> ~/tf-lab/policy/plan.rego <<'EOF'

deny contains msg if {
    some rc in input.resource_changes
    rc.type == "docker_container"
    some p in rc.change.after.ports
    not p.external >= 8000
    msg := sprintf("%s: Port %d nicht in 8000–8999", [rc.address, p.external])
}

deny contains msg if {
    some rc in input.resource_changes
    rc.type == "docker_container"
    some p in rc.change.after.ports
    p.external > 8999
    msg := sprintf("%s: Port %d nicht in 8000–8999", [rc.address, p.external])
}
EOF
conftest fmt --check ~/tf-lab/policy && echo "Rego formatiert"
cd ~/tf-lab/anhb/staging
sed -i 's/port        = 8095/port        = 9095/' main.tf
tofu plan -no-color -out=neu.plan >/dev/null
tofu show -json neu.plan > neu.json
sed -i 's/port        = 9095/port        = 8095/' main.tf
rm neu.plan

Expected:

Rego formatiert

Two rules, because a rule in Rego only matches when all conditions hold – “less than 8000 or greater than 8999” are therefore two rules. Delete neu.json after the check block: it contains the database password in plain text.

Save your progress? Sign up for free

Cleanup

cd ~/tf-lab/anhb/staging
rm -f neu.json
tofu destroy -auto-approve -no-color | tail -1
docker volume ls -q --filter name=stg- | wc -l

Expected:

Destroy complete! Resources: 12 destroyed.
0

The archive volume is gone too: after the import it belongs to OpenTofu, so destroy tears it down.

Knowledge Check

  1. What is in the lock file .terraform.lock.hcl, and why does it belong in Git?
  2. When does OpenTofu update a resource in place, and when does it replace it?
  3. Why is for_each usually better than count for instances?
  4. What happens to a resource when you rename it in the code – and how do you prevent it?
  5. What does sensitive = true protect, and what doesn’t it?
  6. What is use_lockfile = true in the S3 backend for?
  7. Workspaces or one directory per environment: what speaks for directories with dev/prod?
  8. Why is an import block better than tofu import in a team?
  9. What does exit code 2 mean for tofu plan -detailed-exitcode?
  10. Why should a CI pipeline apply the plan from the PR instead of planning again?

Answers

  1. The exact provider versions and their checksums. In Git, it ensures that everyone – and CI – uses the same providers (Day 1).
  2. Update when the provider can adjust the attribute on the running object; replace when it can only be set at creation. The plan shows it with # forces replacement (Day 1).
  3. Instances are tied to names instead of positions. If one goes away, the others stay untouched; with count, the indexes shift (Day 4).
  4. OpenTofu plans a delete and a recreate. A moved block says it’s the same resource (Days 11, 15).
  5. The output in plan and log. In the state, the value is still in plain text (Day 12).
  6. A lock file in the bucket prevents two runs from writing the state at the same time (Day 9).
  7. Every difference is visible in the code; each environment has its own values, its own state, and its own permissions. With workspaces, an invisible setting decides (Day 10).
  8. It goes through review and plan; tofu import changes the state immediately (Day 11).
  9. The plan contains changes – so for a drift check: drift (Day 14).
  10. Only then is exactly what was reviewed actually put into place. If something has changed, OpenTofu rejects the old plan (Day 14).

What’s Next?

  • Kubernetes hands-on: what’s behind the resources from Days 6 and 7.
  • Keycloak hands-on: the identity provider from Day 8 from the inside.
  • GitHub Actions hands-on: the same pipeline as on Day 14, on GitHub.
  • Into the cloud: The providers for AWS, Azure, and Google work just like the Docker provider – with credentials instead of a socket. Start with a bucket and a network, not with a cluster.