I am trying to create a aws_route through terraform .. I have an object which I need to parse and create resources based on all possible combinations .. can someone suggest me how I can do it.?
My var is as below
Test_route = {
Route_table_id_1 = {
Destination = [“10.0.0.0”,”10.1.0.0”]
Nat_id = [“abd”,”sky”]
}
Route_table_id_2 = {
Destination = [“10.0.0.0”,”10.1.0.0”,”0.0.0.0/0”]
Nat_id = [“abd”,”sky”]
}
}
I need to loop in a way as depicted below
resource "aws_route" "private_subnet_route_to_nat_gw" {
route_table_id = "Route_table_id_1 "
destination_cidr_block = “10.0.0.0”
nat_gateway_id = "abc"
route_table_id = "Route_table_id_1 "
destination_cidr_block = ”10.1.0.0”
nat_gateway_id = "abc"
route_table_id = "Route_table_id_1 "
destination_cidr_block = “10.0.0.0”
nat_gateway_id = "sky"
route_table_id = "Route_table_id_1 "
destination_cidr_block = ”10.1.0.0”
nat_gateway_id = "sky"
route_table_id = "Route_table_id_2 "
destination_cidr_block = ”10.1.0.0”
nat_gateway_id = "abc"
route_table_id = "Route_table_id_2 "
destination_cidr_block = ”10.1.0.0”
nat_gateway_id = "sky"
route_table_id = "Route_table_id_2 "
destination_cidr_block = ”10.0.0.0”
nat_gateway_id = "abc"
route_table_id = "Route_table_id_2 "
destination_cidr_block = ”10.0.0.0”
nat_gateway_id = "sky"
route_table_id = "Route_table_id_2 "
destination_cidr_block = ”0.0.0.0/0”
nat_gateway_id = "abc"
route_table_id = "Route_table_id_2 "
destination_cidr_block = ”0.0.0.0/0”
nat_gateway_id = "sky"
}
I tried with for loops and for_each but was failing in looping through all the possible scenarios
You have to flatten your variable:
locals {
flat_Test_route = merge(flatten([
for rt_id, rt_details in var.Test_route:[
for destination in rt_details.Destination: {
for nat_id in rt_details.Nat_id:
"${rt_id}-${destination}-${nat_id}" => {
"rt_id" = rt_id
"destination" = destination
"nat_id" = nat_id
}
}
]
])...) # do NOT remove the dots
}
then
resource "aws_route" "private_subnet_route_to_nat_gw" {
for_each = local.flat_Test_route
route_table_id = each.value.rt_id
destination_cidr_block = each.value.destination
nat_gateway_id = each.value.nat_id
}