For Expressions and Iteration
You'll learn how to transform collections dynamically using Terraform's for expressions to create new lists and maps from existing data.
What Are For Expressions?
Think of for expressions like a conveyor belt in a factory: you feed items in one end, transform each one according to your rules, and collect the results at the other end. In Terraform, you use for expressions to loop through lists or maps, apply transformations, and produce new collections—all within a single expression.
Transforming Lists
You can iterate over a list to create a new one:
variable "instance_ids" {
default = ["i-123", "i-456", "i-789"]
}
locals {
uppercase_ids = [for id in var.instance_ids : upper(id)]
# Result: ["I-123", "I-456", "I-789"]
}
Each element flows through the expression, gets transformed by upper(), and lands in the new list.
Transforming Maps
You can also iterate over maps and reshape them:
variable "tags" {
default = {
env = "dev"
app = "web"
}
}
locals {
prefixed_tags = {for k, v in var.tags : k => "prefix-${v}"}
# Result: {env = "prefix-dev", app = "prefix-web"}
}
Notice the k, v syntax captures both key and value, and => creates the new map entries.
List to Map Conversion
Transform a list into a map with custom keys:
locals {
ids_as_map = {for id in var.instance_ids : id => "active"}
# Result: {"i-123" = "active", "i-456" = "active", "i-789" = "active"}
}
Key Takeaway: For expressions let you iterate and transform collections inline, creating dynamic infrastructure configurations from existing data without repetitive code blocks.