Hi guys,
I’m importing existing resources into Terraform and one thing I’m currently stuck is to import multiple route tables with routes… I have created route map in the following format that I’m passing to the vpc module:
additional_route_tables = {
rtb1 = {
rtb_name = "myrtb1"
routes = [
{
cidr_block = "0.0.0.0/0"
nat_gateway_id = "nat-xxxxxxxxx"
},
{
transit_gateway_id = "tgw-xxxxxxx"
cidr_block = "x.x.x.x/x"
}
]
},
rtb2 = {
rtb_name = "myrtb2"
routes = [
{
cidr_block = "0.0.0.0/0"
gateway_id = "igw-xxxxxxxxxxxxxx"
},
{
vpc_endpoint_id = "vpce-xxxxxxxxxxxx"
cidr_block = "x.x.x.x/x"
}
]
}
}
In the module, I’m extracting the routes and creating a local variable:
locals {
rtb_routes = flatten([
for k, v in var.additional_route_tables : [
v["routes"]
]
])
}
and then use aws_route_table resource with dynamic module:
resource "aws_route_table" "default" {
for_each = var.additional_route_tables
vpc_id = aws_vpc.vpc.id
dynamic "route" {
for_each = local.rtb_routes
content {
cidr_block = route.value.cidr_block
ipv6_cidr_block = lookup(route.value, "ipv6_cidr_block", null)
egress_only_gateway_id = lookup(route.value, "egress_only_gateway_id", null)
gateway_id = lookup(route.value, "gateway_id", null)
instance_id = lookup(route.value, "instance_id", null)
nat_gateway_id = lookup(route.value, "nat_gateway_id", null)
network_interface_id = lookup(route.value, "network_interface_id", null)
transit_gateway_id = lookup(route.value, "transit_gateway_id", null)
vpc_endpoint_id = lookup(route.value, "vpc_endpoint_id", null)
vpc_peering_connection_id = lookup(route.value, "vpc_peering_connection_id", null)
}
}
tags = merge(
{
"Name" = each.value["rtb_name"]
},
local.common_tags
)
}
It creates two route tables, however, it adds up all the routes and create those routes in both rtb. In the example above, it will add four routes in each of the route table. I tried several other combinations but I’m not able to produce the required output.
Can you please suggest the workaround for this problem?
Thanks much,
Karan