Cheat notes · Module 02 · The loop
Inputs, locals, outputs and validation
A five-minute review for when you have done this module and want it back in your head. Open the full module for the steps and the lab, or the full text to print.
The idea
Variables are typed inputs with rules, locals name an expression once, and outputs publish values. Validation refuses bad input before any plan; it cannot tell a valid value from the right one.
Remember
variable: type, optional default, description, andvalidation { condition, error_message }.optional(number, 10)in an object type gives a field its default.- Local:
local.namespace, computed once, not an input. - Precedence, later wins: default,
TF_VAR_name,terraform.tfvars,*.auto.tfvars(alphabetical),-varand-var-file. - **
*.auto.tfvars** is loaded automatically and is often ignored by Git.
Pitfalls
- A leftover
zz-local.auto.tfvarssetsenvironment = "prod": the plan replaces everything andgit statusis clean. Askterraform console, not Git. - Copying a literal into three places instead of a local: one of them is forgotten in the next change.
Commands
terraform console | Evaluate an expression: var.environment, local.namespace |
terraform plan -var environment=staging | Plan with one input changed, this run only |
terraform output -raw checkout_namespace | One output, without quotes |
ls -a | Files Git may be hiding |
envs/dev/variables.tf (module 02)
variable "environment" {
description = "Which environment this directory manages."
type = string
validation {
condition = contains(["dev", "prod"], var.environment)
error_message = "environment must be dev or prod."
}
}
Test yourself
Answer in your head first, then open the answer.
When does a validation block run?
Before the plan, when the value is set.
terraform.tfvars says dev but the plan uses prod. Where do you look?
*.auto.tfvars files and -var flags; terraform console shows the value in use.
Variable, local or output: the namespace name built from team and environment?
A local.
Where module 02 leaves you: The same objects in checkout-dev, now with labels team, environment, tier and app.kubernetes.io/managed-by=terraform. envs/dev has variables.tf, terraform.tfvars and outputs.tf. terraform plan says No changes.