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 underanhb/….
source ~/tf-lab/setup/env.sh
mkdir -p ~/tf-lab/anhb && cd ~/tf-lab/anhbExercise 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/healthzExpected:
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 -1Expected:
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 HEADExpected:
v1.3.0
cd ~/tf-lab/anhb/staging && tofu output -raw proxy; echoExpected:
stg-proxy
cd ~/tf-lab/module/notes-docker && tofu test -no-color -filter=tests/plan.tftest.hcl \
| tail -1Expected (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-archivExpected:
stg-archiv
Check block:
cd ~/tf-lab/anhb/staging && tofu state list | grep archivExpected:
docker_volume.archiv
tofu plan -no-color | tail -1Expected:
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.tfExpected: 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.planExpected:
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 -lExpected:
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
- What is in the lock file
.terraform.lock.hcl, and why does it belong in Git? - When does OpenTofu update a resource in place, and when does it replace it?
- Why is
for_eachusually better thancountfor instances? - What happens to a resource when you rename it in the code – and how do you prevent it?
- What does
sensitive = trueprotect, and what doesn’t it? - What is
use_lockfile = truein the S3 backend for? - Workspaces or one directory per environment: what speaks for directories with dev/prod?
- Why is an
importblock better thantofu importin a team? - What does exit code 2 mean for
tofu plan -detailed-exitcode? - Why should a CI pipeline apply the plan from the PR instead of planning again?
Answers
- The exact provider versions and their checksums. In Git, it ensures that everyone – and CI – uses the same providers (Day 1).
- 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). - Instances are tied to names instead of positions. If one goes away,
the others stay untouched; with
count, the indexes shift (Day 4). - OpenTofu plans a delete and a recreate. A
movedblock says it’s the same resource (Days 11, 15). - The output in plan and log. In the state, the value is still in plain text (Day 12).
- A lock file in the bucket prevents two runs from writing the state at the same time (Day 9).
- 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).
- It goes through review and plan;
tofu importchanges the state immediately (Day 11). - The plan contains changes – so for a drift check: drift (Day 14).
- 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.