for expression
What is for expression?
for expression: Transforms one collection into another. Square brackets build a list (tuple); braces build a map (object). A for expression in Terraform transforms one collection into another. [for name in var.names : upper(name)] builds a list of uppercase names. Curly braces build a map instead, such as {for u in var.users : u.id => u.email}.
Frequently asked questions about for expression
How is for expression used in practice?
You can also filter with an if clause, as in [for s in var.servers : s.name if s.public].
What should you keep in mind with for expression?
This is how you reshape input data into exactly what a resource or module needs, without repeating yourself. It is the Terraform equivalent of map and filter in other languages. Keep the expressions short, and put complex ones in a locals block with a descriptive name. That keeps resource blocks readable and lets you test the transformation in terraform console on its own.
What does an example of for expression look like?
upper_names = [for n in var.names : upper(n)] by_id = {for u in var.users : u.id => u.name} At a glance
| Category | Terraform |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |