Terraform For Loop
The syntax of a for
loop changes depending on whether you are processing a map
or a list
.
As a reminder, a simple map comprises of a key and value as depicted below.
# variables.tf
simplemapvariable = {
Key = "Value",
}
A map of map comprises of key and value inside a key as depicted below.
# variables.tf
simplemapmapvariable ={
"Key1" = {
Key2 = "Value2"
}
}
To loop over this map of map structure you will need 2 for loops:
# main.tf
output "c_simplemapvariable_6" {
value = flatten([
for Key1, Value1 in var.vnets : [ # First for loop
for Key2,Value2 in Value1 : { # Second for loop
subnet_name = Key2
subnet = Value2
vnet = Key1
}
]
])
}
1. Worked Example.
Assuming you have a list of virtual networks or VPCs that contain subnets like the below
# variables.tfvars
vnets ={
"vn-erp-app" = {
sn-web = "10.10.10.0/24",
sn-app = "10.10.11.0/24"
sn-db = "10.10.12.0/24"
},
"vn-crm-app" = {
sn-web = "10.10.20.0/24",
sn-app = "10.10.21.0/24"
sn-db = "10.10.22.0/24"
}
}
# variables.tf
variable "vnets"{
type = map(map(string))
}
To iterate over this structure you will need to perform 2 loops, as depicted below.
flowchart LR
subgraph For_Loop1[<i>For Loop 1, Iteration 1</i>]
A[<b>vNet:</b> vn-erp-app ] -->B[<b>Network:</b> sn-web = 10.10.10.0/24,sn-app = 10.10.11.0/24, sn-db = 10.10.12.0/24]
subgraph For_Loop2[<i>For Loop 2, Iteration 1</i>]
C[<b>Subnet_name:</b> sn-web] --> D[<b>Subnet:</b> 10.10.10.0/24]
end
end
B-->C
style For_Loop1 fill:#FFFFFF,stroke:#333,stroke-width:1px, stroke-dasharray: 2
style For_Loop2 fill:#FFFFFF,stroke:#333,stroke-width:1px, stroke-dasharray: 2
This is reflected in the following code:
# main.tf
output "c_simplemapvariable_5" {
value = flatten([
for vNet, Network in var.vnets : [
for Subnet_name,Subnet in Network : {
subnet_name = Subnet_name
subnet = Subnet
vnet = vNet
}
]
])
}
c_simplemapvariable_5 = [
{
"subnet" = "10.10.21.0/24"
"subnet_name" = "sn-app"
"vnet" = "vn-crm-app"
},
{
"subnet" = "10.10.22.0/24"
"subnet_name" = "sn-db"
"vnet" = "vn-crm-app"
},
{
"subnet" = "10.10.20.0/24"
"subnet_name" = "sn-web"
"vnet" = "vn-crm-app"
},
{
"subnet" = "10.10.11.0/24"
"subnet_name" = "sn-app"
"vnet" = "vn-erp-app"
},
{
"subnet" = "10.10.12.0/24"
"subnet_name" = "sn-db"
"vnet" = "vn-erp-app"
},
{
"subnet" = "10.10.10.0/24"
"subnet_name" = "sn-web"
"vnet" = "vn-erp-app"
},
]