For expressions and filtering
Transform an inventory
A for expression builds a new value using the elements of an existing collection. Imagine a service inventory containing a name, port and enabled flag for each application. You want only enabled names for a report and a lookup of ports by service name. Neither result creates infrastructure. In an isolated local configuration:
variable "services" { type = list(object({ name = string enabled = optional(bool, true) port = number })) default = [ { name = "search", port = 8080 }, { name = "archive", port = 8081, enabled = false }, { name = "catalog", port = 8082 } ]}
output "enabled_names" { value = [for svc in var.services : svc.name if svc.enabled]}
output "ports_by_name" { value = { for svc in var.services : svc.name => svc.port }}Predicted enabled names: ["search", "catalog"]. The port lookup has three entries: search → 8080, archive → 8081, catalog → 8082. The first output follows the input list order. The second includes disabled services because its expression has no filter. The optional enabled attribute defaults to true, including when a caller supplies null for that attribute; a caller must still supply name and port.
Read the expression from left to right
The name after for is a temporary binding, not a declared input variable. in identifies the source, the colon separates the iteration from the transformation, and the optional final if determines inclusion. Try these independent console expressions:
[for n in [2, 4, 6] : n * 10][for i, n in ["edge", "core"] : "${i}-${n}"][for n in [2, 4, 6] : n if n > 4]{ for k, v in { app = "shop", env = "test" } : k => "tag-${v}" }Predicted results in order: [20, 40, 60], ["0-edge", "1-core"], [6], and an object with app = "tag-shop" and env = "tag-test". With two bindings, the first is the zero-based index for a list/tuple or the key for a map/object; the second is the value. Square brackets construct a tuple; braces and => construct an object. Terraform can convert these values when a compatible list or map is required.
Group repeated keys deliberately
Suppose several service names belong to the same deployment tier. A lookup keyed by tier cannot store one name per key without losing the one-to-many relationship. The grouping marker belongs after the result value:
locals { inventory = { search = "edge" billing = "core" catalog = "edge" }}
output "services_by_tier" { value = { for name, tier in local.inventory : tier => name... }}Predicted result: core = ["billing"], edge = ["catalog", "search"]. In this example the map is visited in key order. Grouping preserves both edge services. Removing ... produces a duplicate-key error, not a last-write-wins result. Use stable unique service IDs as keys when one record per service is intended. Use grouping only when a collection per key is the intended output.
Check boundaries before using the result
An empty source list produces an empty tuple, and an empty source object produces an empty object when using the corresponding delimiters. A filter that rejects every element also gives an empty result. A null source is different: normalize it or reject it in the variable contract before iterating. A filter must evaluate to a boolean. Unknown inputs can make the result unknown during planning. For example, an enabled flag that depends on a provider result may prevent Terraform from deciding which names to include. Do not treat unknown as false. The inventory fixture rejects non-convertible ports and duplicate names in its lookup; those are deliberate negative tests, not runtime-verified diagnostics.
Choose the correct repetition mechanism
Use for to compute values, for_each on a resource or module to declare instances, and dynamic for supported repeatable nested blocks (covered later). Producing three names in an output does not create three resources. Practice filtering the inventory, then choose whether each downstream consumer needs an ordered sequence or a lookup keyed by service identity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
For expressions and filtering — knowledge check
Check collection transformation and projection.
What does the enabled_names expression return for the default inventory?
What does a for expression using square brackets directly construct?
What happens if the ports_by_name expression generates two identical keys?
How do you intentionally group many names under a tier key?
Does a for expression yielding three names create three infrastructure instances?