Scalable Terraform Configuration Design · Topic 2 of 4
Tracing Values and for_each Instances
Terraform Professional 002: trace a value through variables, locals and outputs, find the source of a bug, and read the addresses for_each creates.
- 5 min
- Includes a diagram
- Trace backward: output, then local, then variable, then the source of that variable.
-varand-var-filebeat auto files, which beatterraform.tfvars, which beatsTF_VAR_, which beats the default.- Child modules get values only from
moduleblock arguments and expose them only through outputs.
What it is
Tracing means following one value through the configuration to find why it has the value it has. Most real bugs are a wrong input, a precedence surprise or a reference to the wrong scope, not a broken resource.
Tracing for_each means working out which instances exist, what each address is, and how to refer to one of them or to all of them.
How it works
Where a variable value comes from
For a root module, later sources in this list override earlier ones. A child module has only one source: the arguments in its module block.
| Order | Source |
|---|---|
| 1 | default in the variable block |
| 2 | TF_VAR_name environment variable |
| 3 | terraform.tfvars, then terraform.tfvars.json |
| 4 | *.auto.tfvars and *.auto.tfvars.json files, in lexical filename order |
| 5 | -var and -var-file, in command-line order, and HCP Terraform variables |
Walkthrough: why is the type wrong?
variable "size" {
type = string
default = "small"
}
locals {
sizes = { small = "t3.micro", large = "m5.large" }
instance_type = lookup(local.sizes, var.size, "t3.nano")
}
output "type" {
value = local.instance_type
}
Someone runs terraform apply -var='size=medium' and asks why the output is t3.nano. Trace it backward:
output.typereadslocal.instance_type.- That local is a
lookuponlocal.sizeswith keyvar.size. var.sizeis"medium", because-varbeats the default.- The map has no
mediumkey, solookupreturns its third argument,"t3.nano".
The fix belongs at the source: add the key, or validate the variable so medium is rejected. Writing local.sizes[var.size] would have failed loudly instead of falling back.
Scope and null traps
| Symptom | Cause |
|---|---|
Default ignored when a caller passes null | nullable defaults to true, so null overrides the default; nullable = false makes null use the default |
Unsupported attribute on module.net.x | The child module has no output "x" |
| Child cannot read a parent's variable | Child modules receive values only through arguments in the module block |
| Root output cannot see a nested value | Each module level must pass it up with its own output |
"5" accepted by a number variable | Terraform converts the string to a number automatically |
aws_subnet.this[*].id fails | Splat works on lists, not on the map of instances from for_each |
Walkthrough: for_each addresses
variable "subnets" {
type = map(string)
default = {
app = "10.0.1.0/24"
db = "10.0.2.0/24"
}
}
resource "aws_subnet" "this" {
for_each = var.subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value
}
Terraform creates one instance per map key. For the db instance, each.key is "db" and each.value is "10.0.2.0/24".
terraform state list
terraform state show 'aws_subnet.this["db"]'
The list shows aws_subnet.this["app"] and aws_subnet.this["db"]. Inside a module named net, the same instance is module.net.aws_subnet.this["db"].
| You want | Expression | Result type |
|---|---|---|
| One instance | aws_subnet.this["db"].id | String |
| Map of key to ID | { for k, s in aws_subnet.this : k => s.id } | Object |
| All IDs | values(aws_subnet.this)[*].id | List, in key order |
for_each rules that decide the answer
- The value must be a map or a set of strings. A list is rejected, so wrap it in
toset(), which also removes duplicates and discards order. - With a set,
each.valueis the same aseach.key. - Keys must be known before apply and cannot come from impure functions such as
uuidortimestamp. - Sensitive values cannot be used as
for_eacharguments. - A
for_eachresource can feed another one directly, as infor_each = aws_vpc.main, when the two map one to one. Theneach.valueis the whole upstream instance.
Removing the db key destroys only that instance. Renaming a key is a destroy and create unless a moved block maps the old key to the new one.
How the exam asks about this
- "An output shows the fallback value instead of the expected one." Trace back to the lookup default or the variable source; the key or the input is wrong.
- "Which address refers to the prod instance?" Use the bracketed string key, such as
aws_instance.app["prod"]. - "for_each is given a list of strings and the plan errors." Convert it with toset().
What to remember for the exam
- Trace backward: output, then local, then variable, then the source of that variable.
-varand-var-filebeat auto files, which beatterraform.tfvars, which beatsTF_VAR_, which beats the default.- Child modules get values only from
moduleblock arguments and expose them only through outputs. - A
for_eachresource is a map of instances; usevalues()or aforexpression to get all attributes. for_eachneeds a map or set of strings, with keys known before apply and no sensitive values.
Quote for_each addresses in the shell. In Unix-style shells write 'aws_subnet.this["db"]', because unquoted brackets and double quotes are changed by the shell before Terraform sees them.
Common mistakes
Assuming a passed null means "use the default". With the default nullable = true, an explicit null overwrites the default. Set nullable = false if callers should fall back to it.
Using a numeric index on a for_each resource. aws_subnet.this[0] looks up a key that does not exist. Instances are addressed by their string key.
Fixing the symptom at the output. Patching the output hides the bug for that one consumer. Follow the value back and correct the input or the expression.
Check yourself
A variable has a default, and
TF_VAR_regionand-varboth set it. Which value wins?The
-varvalue, because command-line variables are applied after environment variables and defaults.What does
each.valuereturn whenfor_eachis a set of strings?The same string as
each.key, because a set has only members and no separate values.How do you output every ID from a
for_eachresource?Use
values(aws_subnet.this)[*].idfor a list of IDs, or aforexpression to keep a map of key to ID. A direct splat on the resource does not work.
Topic 2 of 4 in Scalable Terraform Configuration Design
Test yourself on Scalable Terraform Configuration Design
The full HashiCorp Terraform Infrastructure Engineer Professional question bank has 600 questions, with timed practice exams and an explanation for every answer.
This study guide is independent and is not affiliated with, endorsed by, or sponsored by HashiCorp. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.