TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Terraform & OpenTofu Exercises

Terraform & OpenTofu Exercises

Each exercise starts from a real session that shows a problem: a plan that destroys too much, a test that fails, a linter that complains. Change the code (copy the session into your own terminal, or edit it in the playground and compare with the saved output) until it produces the expected output, then compare with the solution. Every solution below is a verified session.

Exercise 1: Remove a team without collateral damage

Topics: count, for_each, moved & removed

Three team folders are managed with count. Removing billing should destroy exactly one file, but the plan replaces another as well. Switch the resource to for_each without recreating the files that already exist, then remove billing.

bash · try it yourself
mkdir teams && cd teams
cat > main.tf <<'HCL'
variable "teams" {
  type    = list(string)
  default = ["api", "billing", "search"]
}
resource "local_file" "team" {
  count    = length(var.teams)
  filename = "team-${var.teams[count.index]}.txt"
  content  = "${var.teams[count.index]}\n"
}
HCL
tofu init >/dev/null && tofu apply -auto-approve >/dev/null
tofu plan -var 'teams=["api", "search"]' | grep -E '^  #|^Plan:'
  # local_file.team[1] must be replaced
  # local_file.team[2] will be destroyed
  # (because index [2] is out of range for count)
Plan: 1 to add, 0 to change, 2 to destroy.

Expected output of your final plan (after the refactor, removing billing):

text
  # local_file.team[0] has moved to local_file.team["api"]
  # local_file.team["billing"] will be destroyed
  # (because key ["billing"] is not in for_each map)
  # (moved from local_file.team[1])
  # local_file.team[2] has moved to local_file.team["search"]
Plan: 0 to add, 0 to change, 1 to destroy.
Show solution
bash · try it yourself
mkdir teams && cd teams
cat > main.tf <<'HCL'
variable "teams" {
  type    = list(string)
  default = ["api", "billing", "search"]
}
resource "local_file" "team" {
  count    = length(var.teams)
  filename = "team-${var.teams[count.index]}.txt"
  content  = "${var.teams[count.index]}\n"
}
HCL
tofu init >/dev/null && tofu apply -auto-approve >/dev/null
# the refactor: for_each keyed by name, plus one moved block per existing index
cat > main.tf <<'HCL'
variable "teams" {
  type    = set(string)
  default = ["api", "billing", "search"]
}
resource "local_file" "team" {
  for_each = var.teams
  filename = "team-${each.key}.txt"
  content  = "${each.key}\n"
}
moved {
  from = local_file.team[0]
  to   = local_file.team["api"]
}
moved {
  from = local_file.team[1]
  to   = local_file.team["billing"]
}
moved {
  from = local_file.team[2]
  to   = local_file.team["search"]
}
HCL
tofu plan -var 'teams=["api", "search"]' | grep -E '^  #|^Plan:'
  # local_file.team[0] has moved to local_file.team["api"]
  # local_file.team["billing"] will be destroyed
  # (because key ["billing"] is not in for_each map)
  # (moved from local_file.team[1])
  # local_file.team[2] has moved to local_file.team["search"]
Plan: 0 to add, 0 to change, 1 to destroy.

The moved blocks map each old index to its new key, so nothing is recreated; only billing is destroyed. In practice you would apply the refactor first (zero changes) and remove the team in a second pull request.

Exercise 2: Reject bad input, and prove it

Topics: Variables, Testing

The test expects cidr = "10.0.0.0/33" to be rejected, but the module accepts anything. Add a validation block so that both runs pass.

bash · try it yourself
mkdir -p net/tests && cd net
cat > main.tf <<'HCL'
variable "cidr" {
  type = string
}
output "first_subnet" {
  value = cidrsubnet(var.cidr, 8, 0)
}
HCL
cat > tests/cidr.tftest.hcl <<'HCL'
run "valid" {
  command = plan
  variables {
    cidr = "10.0.0.0/16"
  }
  assert {
    condition     = output.first_subnet == "10.0.0.0/24"
    error_message = "wrong subnet"
  }
}
run "invalid_prefix_is_rejected" {
  command = plan
  variables {
    cidr = "10.0.0.0/33"
  }
  expect_failures = [var.cidr]
}
HCL
tofu init >/dev/null
tofu test 2>&1 | grep -E 'run "|passed|failed'
  run "valid"... pass
  run "invalid_prefix_is_rejected"... fail
Call to function "cidrsubnet" failed: invalid CIDR expression: invalid CIDR
  on tests/cidr.tftest.hcl line 16, in run "invalid_prefix_is_rejected":
Failure! 1 passed, 1 failed.

Expected output:

text
  run "valid"... pass
  run "invalid_prefix_is_rejected"... pass
Success! 2 passed, 0 failed.
Show solution
bash · try it yourself
mkdir -p net/tests && cd net
cat > main.tf <<'HCL'
variable "cidr" {
  type = string
  validation {
    condition     = can(cidrhost(var.cidr, 0))
    error_message = "cidr must be a valid IPv4 CIDR block, e.g. 10.0.0.0/16."
  }
}
output "first_subnet" {
  value = cidrsubnet(var.cidr, 8, 0)
}
HCL
cat > tests/cidr.tftest.hcl <<'HCL'
run "valid" {
  command = plan
  variables {
    cidr = "10.0.0.0/16"
  }
  assert {
    condition     = output.first_subnet == "10.0.0.0/24"
    error_message = "wrong subnet"
  }
}
run "invalid_prefix_is_rejected" {
  command = plan
  variables {
    cidr = "10.0.0.0/33"
  }
  expect_failures = [var.cidr]
}
HCL
tofu init >/dev/null
tofu test 2>&1 | grep -E 'run "|passed|failed'
  run "valid"... pass
  run "invalid_prefix_is_rejected"... pass
Success! 2 passed, 0 failed.

can(cidrhost(var.cidr, 0)) is false for anything cidrhost can't parse, so the validation fails exactly where the test expects it to.

Exercise 3: An optional resource with a safe output

Topics: count & Conditional Resources, Outputs & Locals

Make the bastion file optional with a boolean variable enable_bastion (default false), and make the bastion_file output return null when it is disabled. The starter fails as soon as the resource can have zero instances.

bash · try it yourself
mkdir opt && cd opt
cat > main.tf <<'HCL'
variable "enable_bastion" {
  type    = bool
  default = false
}
resource "local_file" "bastion" {
  count    = var.enable_bastion ? 1 : 0
  filename = "bastion.txt"
  content  = "ssh jump host\n"
}
output "bastion_file" {
  value = local_file.bastion.filename
}
HCL
tofu init >/dev/null
tofu plan 2>&1 | grep -E 'Error|Because|instances'
Error: Missing resource instance key
Because local_file.bastion has "count" set, its attributes must be accessed
on specific instances.

Expected output of tofu output -json | jq '.bastion_file.value', after applying with the default and then with -var enable_bastion=true:

text
null
"bastion.txt"
Show solution
bash · try it yourself
mkdir opt && cd opt
cat > main.tf <<'HCL'
variable "enable_bastion" {
  type    = bool
  default = false
}
resource "local_file" "bastion" {
  count    = var.enable_bastion ? 1 : 0
  filename = "bastion.txt"
  content  = "ssh jump host\n"
}
output "bastion_file" {
  value = one(local_file.bastion[*].filename)
}
HCL
tofu init >/dev/null
tofu apply -auto-approve >/dev/null && tofu output -json | jq '.bastion_file.value'
tofu apply -auto-approve -var enable_bastion=true >/dev/null && tofu output -json | jq '.bastion_file.value'
null
"bastion.txt"

With count, the resource is a list; one() returns its only element, or null for an empty list. A null output counts as "not set" and isn't stored in state at all: tofu output bastion_file would fail with Output "bastion_file" not found, so scripts read all outputs as JSON and treat a missing key as null, as jq does here.

Exercise 4: Make tflint pass

Topics: Linting with tflint, Variables

Fix the code (don't silence the rules) until tflint exits with 0.

bash · try it yourself
mkdir lint && cd lint
cat > .tflint.hcl <<'HCL'
plugin "aws" {
  enabled = true
  version = "0.50.0"
  source  = "github.com/terraform-linters/tflint-ruleset-aws"
}
HCL
cat > main.tf <<'HCL'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}
variable "instance_type" {
  default = "t3.mircro"
}
resource "aws_instance" "web" {
  ami           = "ami-0123456789abcdef0"
  instance_type = var.instance_type
}
HCL
tflint --format compact > out.txt; echo "exit=$?"
grep '^main' out.txt | sort -t: -k2,2n -k3,3n
exit=2
main.tf:1:1: Warning - terraform "required_version" attribute is required (terraform_required_version)
main.tf:6:1: Warning - `instance_type` variable has no type (terraform_typed_variables)
main.tf:11:19: Error - "t3.mircro" is an invalid value as instance_type (aws_instance_invalid_type)
Show solution
bash · try it yourself
mkdir lint && cd lint
cat > .tflint.hcl <<'HCL'
plugin "aws" {
  enabled = true
  version = "0.50.0"
  source  = "github.com/terraform-linters/tflint-ruleset-aws"
}
HCL
cat > main.tf <<'HCL'
terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}
variable "instance_type" {
  type    = string
  default = "t3.micro"
}
resource "aws_instance" "web" {
  ami           = "ami-0123456789abcdef0"
  instance_type = var.instance_type
}
HCL
tflint --format compact; echo "exit=$?"
exit=0

tflint also evaluated the variable's default to catch t3.mircro through var.instance_type. Three fixes: required_version, a type, and the typo.

Exercise 5: Find the replacement before it finds you

Topics: init, plan, apply & destroy in Depth, Field Notes

Write a jq filter over tofu show -json tfplan that prints only the addresses that will be replaced, so a CI job can fail on them. The starter prints every change.

bash · try it yourself
mkdir r && cd r
cat > main.tf <<'HCL'
variable "v" {
  type    = string
  default = "1"
}
resource "local_file" "a" {
  filename = "a.txt"
  content  = "a${var.v}\n"
}
resource "terraform_data" "b" {
  input = "b${var.v}"
}
resource "terraform_data" "c" {
  input            = "c"
  triggers_replace = [var.v]
}
HCL
tofu init >/dev/null && tofu apply -auto-approve >/dev/null
tofu plan -var v=2 -out=tfplan >/dev/null
tofu show -json tfplan | jq -r '.resource_changes[] | "\(.change.actions) \(.address)"'
["delete","create"] local_file.a
["update"] terraform_data.b
["delete","create"] terraform_data.c

Expected output:

text
local_file.a
terraform_data.c
Show solution
bash · try it yourself
mkdir r && cd r
cat > main.tf <<'HCL'
variable "v" {
  type    = string
  default = "1"
}
resource "local_file" "a" {
  filename = "a.txt"
  content  = "a${var.v}\n"
}
resource "terraform_data" "b" {
  input = "b${var.v}"
}
resource "terraform_data" "c" {
  input            = "c"
  triggers_replace = [var.v]
}
HCL
tofu init >/dev/null && tofu apply -auto-approve >/dev/null
tofu plan -var v=2 -out=tfplan >/dev/null
tofu show -json tfplan | jq -r '.resource_changes[]
  | select((.change.actions | index("delete")) and (.change.actions | index("create")))
  | .address'
local_file.a
terraform_data.c

A replacement is any change whose actions contain both delete and create, in either order (["delete","create"] by default, ["create","delete"] with create_before_destroy). terraform_data.b is an in-place update and is correctly left out.

Test yourself

In Exercise 1, why are moved blocks needed when switching from count to for_each?

  1. for_each requires them
  2. The addresses change from [0] to ["api"]; without moves, every file would be destroyed and recreated
  3. To delete billing
  4. To update the lock file

What does one(local_file.bastion[*].filename) return when count = 0?

  1. An error
  2. An empty string
  3. null
  4. An empty list

Which actions value in plan JSON means a replacement with create_before_destroy?

  1. ["update"]
  2. ["create","delete"]
  3. ["delete"]
  4. ["no-op"]