0
0
TerraformHow-ToBeginner · 3 min read

How to Use For Expression in Terraform: Syntax and Examples

In Terraform, a for expression lets you create new lists or maps by looping over existing collections. You write it as [for item in list : expression] for lists or {for key, value in map : key => expression} for maps, which helps generate values dynamically.
📐

Syntax

The for expression in Terraform has two main forms: one for lists and one for maps.

  • List form: [for item in list : expression] creates a new list by applying expression to each item.
  • Map form: {for key, value in map : key => expression} creates a new map by applying expression to each value with its key.

This lets you transform or filter collections easily.

terraform
[for item in var.names : "Hello, ${item}!"]

{for k, v in var.ages : k => v + 1}
💻

Example

This example shows how to use a for expression to create a list of greetings from a list of names, and a map with incremented ages.

terraform
variable "names" {
  type    = list(string)
  default = ["Alice", "Bob", "Carol"]
}

variable "ages" {
  type    = map(number)
  default = {
    Alice = 30
    Bob   = 25
    Carol = 27
  }
}

output "greetings" {
  value = [for name in var.names : "Hello, ${name}!"]
}

output "incremented_ages" {
  value = {for person, age in var.ages : person => age + 1}
}
Output
greetings = ["Hello, Alice!", "Hello, Bob!", "Hello, Carol!"] incremented_ages = { Alice = 31 Bob = 26 Carol = 28 }
⚠️

Common Pitfalls

Common mistakes when using for expressions include:

  • Forgetting the colon : after the in clause.
  • Using incorrect brackets: lists require square brackets [], maps require curly braces {}.
  • Not matching the output type with the expression (e.g., trying to create a map but using list syntax).
  • Using variables or attributes that don't exist in the loop.

Always check syntax carefully and test outputs.

terraform
/* Wrong: missing colon after 'in' */
[for item in var.list "${item}_suffix"]

/* Correct: colon included */
[for item in var.list : "${item}_suffix"]
📊

Quick Reference

PartDescriptionExample
forStarts the loopfor item in var.list
inSpecifies the collection to loop overin var.list
:Separates loop from expression:
expressionValue to produce for each item"Hello, ${item}!"
[]Wraps for list output[for item in var.list : expression]
{}Wraps for map output{for k, v in var.map : k => v + 1}

Key Takeaways

Use square brackets [] for list comprehensions and curly braces {} for maps in for expressions.
Always include a colon : after the in clause to separate the loop from the expression.
For expressions let you transform or filter collections dynamically in Terraform.
Check your syntax carefully to avoid common errors like missing colons or wrong brackets.
For expressions improve code readability and reduce repetition in Terraform configurations.