Skip to content
Hands-on IT IT Drills

Day 2: Variables, Outputs, locals

Goal: Control a configuration from the outside with variables, validate values, compute with locals and expressions, emit results as outputs, and generate files from templates. · Duration: approx. 75 min · Prerequisite: Day 1

Briefing

  • variable is the input of a configuration: with type, default value, description, and validation (validation). It is read as var.name.
  • Values come from -var, from *.tfvars files, or from environment variables TF_VAR_name.
  • locals are intermediate results inside the configuration (local.name), output is the output: values that are shown after apply and used by others.
  • HCL has expressions: "${var.a}-x", var.p ? 1 : 2, [for k, v in map : …], functions like upper, join, merge, templatefile.
 -var / *.tfvars / TF_VAR_*  ─► variable ─► locals ─► resource ─► output
                                    └ validation   └ templatefile("index.html.tftpl")

Drill 1: Variables

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

provider "docker" {}
EOF
cat > variables.tf <<'EOF'
variable "umgebung" {
  description = "Name der Umgebung, Teil aller Namen"
  type        = string
  default     = "dev"
  validation {
    condition     = contains(["dev", "test", "prod"], var.umgebung)
    error_message = "umgebung muss dev, test oder prod sein."
  }
}

variable "port" {
  description = "Port auf 127.0.0.1, unter dem die Seite erreichbar ist"
  type        = number
  default     = 8082
  validation {
    condition     = var.port >= 1024 && var.port <= 65535
    error_message = "port muss zwischen 1024 und 65535 liegen."
  }
}

variable "nginx_version" {
  type    = string
  default = "1.31.8-alpine"
}

variable "team" {
  description = "Wer für die Umgebung verantwortlich ist"
  type        = map(string)
  default     = { name = "Plattform", kontakt = "[email protected]" }
}
EOF
cat > main.tf <<'EOF'
locals {
  name = "notes-web-${var.umgebung}"
  labels = {
    umgebung = var.umgebung
    team     = var.team.name
    verwaltet_von = "opentofu"
  }
}

resource "docker_image" "nginx" {
  name         = "nginx:${var.nginx_version}"
  keep_locally = true
}

resource "docker_container" "web" {
  name  = local.name
  image = docker_image.nginx.image_id
  ports {
    internal = 80
    external = var.port
    ip       = "127.0.0.1"
  }
  dynamic "labels" {
    for_each = local.labels
    content {
      label = labels.key
      value = labels.value
    }
  }
}
EOF
tofu init -no-color >/dev/null && tofu fmt && tofu validate -no-color
tofu plan -no-color | grep -E 'notes-web|external|Plan:'

Expected:

main.tf
Success! The configuration is valid.
      + name                                        = "notes-web-dev"
          + external = 8082
Plan: 2 to add, 0 to change, 0 to destroy.
  • tofu fmt reformatted main.tf: it aligns the = signs in labels. It prints which files it changed.
  • dynamic "labels" generates a labels block for each element of the map – more on that on Day 4.

Save your progress? Sign up for free

Drill 2: Where the Values Come From

tofu plan -no-color -var umgebung=prod | grep 'notes-web'
echo 'umgebung = "test"' > test.tfvars
tofu plan -no-color -var-file=test.tfvars | grep 'notes-web'
TF_VAR_port=9090 tofu plan -no-color | grep 'external'
tofu plan -no-color -var umgebung=staging 2>&1 | grep -A2 'Invalid value'
tofu plan -no-color -var port=80 2>&1 | grep -E 'port muss'

Expected:

      + name                                        = "notes-web-prod"
      + name                                        = "notes-web-test"
          + external = 9090
Error: Invalid value for variable

  on variables.tf line 1:
port muss zwischen 1024 und 65535 liegen.
Source Precedence
default in the variable lowest
TF_VAR_name
terraform.tfvars, *.auto.tfvars (loaded automatically)
-var-file=…
-var name=… highest

The validations run before OpenTofu plans anything – a wrong value never reaches Docker.

Save your progress? Sign up for free

Drill 3: Outputs

cat > outputs.tf <<'EOF'
output "url" {
  description = "Adresse der Seite"
  value       = "http://127.0.0.1:${var.port}/"
}

output "container" {
  value = {
    name   = docker_container.web.name
    id     = substr(docker_container.web.id, 0, 12)
    labels = local.labels
  }
}
EOF
tofu apply -auto-approve -no-color | grep -A12 '^Outputs:'
curl -s -o /dev/null -w '%{http_code}\n' "$(tofu output -raw url)"
tofu output -json container | jq -c '.labels'

Expected (the ID differs):

Outputs:

container = {
  "id" = "6efb27a9be25"
  "labels" = {
    "team" = "Plattform"
    "umgebung" = "dev"
    "verwaltet_von" = "opentofu"
  }
  "name" = "notes-web-dev"
}
url = "http://127.0.0.1:8082/"
200
{"team":"Plattform","umgebung":"dev","verwaltet_von":"opentofu"}

tofu output -raw returns text without quotes – just right for scripts. -json prints maps and lists so that jq can read them.

Save your progress? Sign up for free

Drill 4: Expressions and Templates

In the project folder, tofu console knows all variables, locals, and resources:

cat <<'EOF' | tofu console
local.name
upper(var.team.name)
var.umgebung == "prod" ? "streng" : "locker"
[for k, v in local.labels : "${k}=${v}"]
join(",", sort(keys(local.labels)))
EOF

Expected:

"notes-web-dev"
"PLATTFORM"
"locker"
[
  "team=Plattform",
  "umgebung=dev",
  "verwaltet_von=opentofu",
]
"team,umgebung,verwaltet_von"

Now the page gets its own content from a template:

cat > index.html.tftpl <<'EOF'
<h1>notes – ${upper(umgebung)}</h1>
<p>Verantwortlich: ${team.name} (${team.kontakt})</p>
%{ for k in sort(keys(labels)) ~}
<p>${k}: ${labels[k]}</p>
%{ endfor ~}
EOF
cat > web.tf <<'EOF'
locals {
  startseite = templatefile("${path.module}/index.html.tftpl", {
    umgebung = var.umgebung
    team     = var.team
    labels   = local.labels
  })
}
EOF
cat > upload.txt <<'EOF'
  upload {
    file    = "/usr/share/nginx/html/index.html"
    content = local.startseite
  }
EOF
sed -i '/^  dynamic "labels" {$/e cat upload.txt' main.tf
grep -B1 -A3 'upload {' main.tf
tofu fmt >/dev/null
tofu apply -auto-approve -no-color | grep -E 'must be replaced|Apply complete' \
  | sed 's/^ *//'
curl -s "$(tofu output -raw url)"

Expected:

  }
  upload {
    file    = "/usr/share/nginx/html/index.html"
    content = local.startseite
  }
# docker_container.web must be replaced
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
<h1>notes – DEV</h1>
<p>Verantwortlich: Plattform ([email protected])</p>
<p>team: Plattform</p>
<p>umgebung: dev</p>
<p>verwaltet_von: opentofu</p>
  • sed '/muster/e cat datei' inserts the contents of the file before the matching line.
  • templatefile(datei, werte) fills in a template: ${…} inserts values, %{ for } repeats lines, ~ removes the line break after it.
  • path.module is the configuration’s folder – that way the path works no matter where tofu is called from.
  • A new file in the container replaces the container: Docker can only upload content when creating it.

Save your progress? Sign up for free

Checkpoint

tofu output -raw url; echo

Expected:

http://127.0.0.1:8082/
tofu plan -no-color -detailed-exitcode >/dev/null; echo "Exit: $?"

Expected: configuration and Docker match (0 = nothing to do, 2 = changes).

Exit: 0
tofu plan -no-color -var umgebung=qa 2>&1 | grep -c 'umgebung muss'

Expected:

1

Challenge

Create a file prod.tfvars with which the same configuration describes an environment prod on port 8083 with the team “Betrieb” ([email protected]). Show only the name, the port, and the contact address in the plan – without creating anything.

Hint: A map is written in .tfvars the same way as in HCL.

Solution

cat > prod.tfvars <<'EOF'
umgebung = "prod"
port     = 8083
team = {
  name    = "Betrieb"
  kontakt = "[email protected]"
}
EOF
tofu plan -no-color -var-file=prod.tfvars | grep -E 'notes-web-prod|Plan:'

Expected (whitespace shortened):

      ~ name     = "notes-web-dev" -> "notes-web-prod" # forces replacement
Plan: 1 to add, 0 to change, 1 to destroy.
      ~ name   = "notes-web-dev" -> "notes-web-prod"

The last line belongs to the outputs: there, too, the plan shows what would change. Without grep you also see the new port and the changed start page.

Same code, different values – that’s the foundation for environments (Day 10). Warning: with the same state, the plan would replace the dev page, not create a second one. For that, each environment needs its own state.

Save your progress? Sign up for free

Enterprise Note

  • Document variables: description and validation are part of the interface. Tools like terraform-docs generate a module’s documentation from them.
  • No secrets in .tfvars in Git: Passwords come from TF_VAR_…, a secret file outside the repo, or a vault (Day 12).
  • Consistent labels and tags via locals – cost center, team, environment – make billing and cleanup possible later on.