You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform循环嵌套对象:解决路由表仅添加单条路由问题

嘿,这个问题我之前也踩过坑!原因其实很直白——你在定义route_tables变量时,同一个路由表下重复使用了route这个键,而Terraform的map结构里,相同键会直接覆盖前面的值,最后就只剩最后那条route3了,所以执行tf plan时只会生成一条路由。

要解决这个问题,只需要两步调整:

1. 修正变量结构,把重复的route键改成列表

把每个路由表下的route从重复的map键,改成**列表(list)**结构,这样就能容纳多个路由对象:

variable "route_tables" {
  description = "a map of route tables"
  type        = map(any)

  default = {
    "route_table01" = {
      name = "route_table01"
      route = [
        {
          name                   = "route1"
          address_prefix         = "17.65.255.0/24"
          next_hop_type          = "VirtualAppliance"
          next_hop_in_ip_address = "10.18.128.6"
        },
        {
          name                   = "route2"
          address_prefix         = "204.61.3.87/32"
          next_hop_type          = "VirtualAppliance"
          next_hop_in_ip_address = "10.18.128.6"
        },
        {
          name                   = "route3"
          address_prefix         = "13.61.37.248/29"
          next_hop_type          = "VirtualAppliance"
          next_hop_in_ip_address = "10.18.128.6"
        }
      ]
    }
  }
}

2. 调整dynamic块的遍历逻辑

现在route是列表了,需要修改azurerm_route_table里的dynamic块,正确遍历列表中的每个路由对象:

resource "azurerm_route_table" "route_tables" {
  for_each = var.route_tables

  name                = each.value.name
  location            = azurerm_resource_group.resource_group.location
  resource_group_name = azurerm_resource_group.resource_group.name
  tags                = local.tags
  
  dynamic "route" {
    for_each = each.value.route
    content {
      name                   = route.value.name
      address_prefix         = route.value.address_prefix
      next_hop_type          = route.value.next_hop_type
      next_hop_in_ip_address = route.value.next_hop_in_ip_address
    }
  }
}

这里要注意:dynamic块的迭代器是route,所以用route.value来访问当前遍历到的路由对象属性,而不是原来的each.value.route。

这样修改后,Terraform就会遍历每个路由表下的所有路由条目,把它们都添加到对应的路由表里了。

内容的提问来源于stack exchange,提问作者RNemeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:05:19