I cant seem to figure out how to loop through a set of routes in an azurerm_route resource block. The route table resources consist of over 300+ routes, and i need a way to iterate through the routes as they will add/delete over time.
data.tf
data "azurerm_resource_group" "lab-rg" {
name = var.resource_group_name
}
data "azurerm_route_table" "lab-rt" {
name = var.rtLab1
resource_group_name = data.azurerm_resource_group.lab-rg.name
}
main.tf
resource "azurerm_route" "lab-rt1-routes" {
#for_each = var.route_table["${var.rtLab1}"].routes
for_each = {for idx, route in var.route_table["${var.rtLab1}"].routes: route => idx}
resource_group_name = azurerm_route_table.lab-rt.resource_group_name
route_table_name = azurerm_route_table.lab-rt.name
name = each.value.name
address_prefix = each.value.addressPrefix
next_hop_type = each.value.nextHopType
next_hop_in_ip_address = each.value.nextHopIpAddress
}
variables.tf
variable "resource_group_name" {
default = null
}
variable "location" {
default = null
}
variable "tags" {
type = map(string)
default = null
}
variable "rtLab1" {
default = null
}
variable "rtLab2" {
default = null
}
variable "route_table" {
description = "Route table configuration"
type = map(object({
routes = list(object({
name = string
addressPrefix = string
nextHopType = string
nextHopIpAddress = string
}))
}))
}
terraform.tfvars
resource_group_name = "ACE-L-PALMS-RGP-07-002"
location = "eastus2"
rtLab1 = "ACE-L-SNT-LAB-UDR-001"
rtLab2 = "ACE-L-SNT-LAB-UDR-002"
route_table = {
"ACE-L-SNT-LAB-UDR-001" = {
routes = [
{
name = "Default-0.0.0.0_0-Route",
addressPrefix = "0.0.0.0/0",
nextHopType = "VirtualAppliance",
nextHopIpAddress = "xxx.xxx.xxx.xxx"
},
{
name = "On-Prem-Route1",
addressPrefix = "xxx.xxx.xxx.xxx/24",
nextHopType = "VirtualAppliance",
nextHopIpAddress = "xxx.xxx.xxx.xxx"
},
{
name = "On-Prem-Route2",
addressPrefix = "xxx.xxx.xxx.xxx/24",
nextHopType = "VirtualAppliance",
nextHopIpAddress = "xxx.xxx.xxx.xxx"
}]
},
"ACE-L-SNT-LAB-UDR-002" = {
routes = [
{
addressPrefix = "0.0.0.0/0"
name = "Default-0.0.0.0_0-Route"
nextHopIpAddress = "VirtualAppliance"
nextHopType = "xxx.xxx.xxx.xxx"
}
]
}
}
Not sure, how to loop through the list(object) in the resource “azurerm_route” “lab-rt1-routes” block. I am getting a different error every time I try to change the for_each loop. Either way it seems to not be able to grab the routes in the specific route table it is in. Is there any way to loop through these and pull just the routes to be used in the azurerm_route resource block. The tfvars file, I simplified down to 3 routes but in reality, there is over 350+ routes need to be added to the route table.
Error as is
terraform plan
╷
│ Error: Invalid reference
│
│ on main.tf line 13, in resource "azurerm_route" "lab-rt1-routes":
│ 13: for_each = {for idx, route in var.route_table["${var.rtLab1}"].routes: route => idx}
│
│ A reference to a resource type must be followed by at least one attribute access, specifying the resource name.