Terraform Tutorial · Terraform Language · Lesson 14 of 25
Terraform for Expressions
Transform lists and maps with for expressions: filter, reshape and build new collections.
List and map comprehensions
locals {
users = ["ada", "linus", "grace"]
}
output "upper_names" {
value = [for u in local.users : upper(u)]
}
output "name_lengths" {
value = { for u in local.users : u => length(u) }
}
output "short_names" {
value = [for u in local.users : u if length(u) <= 4]
}
Output
name_lengths = {
"ada" = 3
"grace" = 5
"linus" = 5
}
short_names = [
"ada",
]
upper_names = [
"ADA",
"LINUS",
"GRACE",
]Run this on your computer — see “Get Started” for setup.
[for x in list : expr]builds a list.{for x in list : key => value}builds a map.- Add
if conditionto filter. ...after the value groups duplicate keys into lists.
Reshaping data
locals {
instances = [
{ name = "web-1", zone = "a" },
{ name = "web-2", zone = "b" },
{ name = "db-1", zone = "a" },
]
}
output "by_zone" {
value = { for i in local.instances : i.zone => i.name... }
}
Output
by_zone = {
"a" = [
"web-1",
"db-1",
]
"b" = [
"web-2",
]
}Run this on your computer — see “Get Started” for setup.
Test yourself
Which expression builds a map?
[for u in users : u]{for u in users : u => length(u)}for_each = usersusers[*]
Show answer
Answer: {for u in users : u => length(u)}