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

Terraform如何对嵌套在映射列表中的映射列表使用for_each遍历

问题原因

你的写法存在两个核心问题:

  • for_each 直接传入了列表类型的local.vpn_configurations,Terraform的for_each仅支持传入map或字符串集合,无法直接处理列表
  • 当前遍历的维度是客户VPN配置,而非每个独立隧道,且each.value.tunnels["xxx"]的取值逻辑错误——tunnels是列表类型,无法直接通过属性名批量取所有隧道的对应字段
解决方案

首先定义一个展平所有隧道的本地变量,把两层嵌套列表展开为以{客户名}-{隧道名}为唯一键的map,每个值对应单个隧道的全量信息:

locals {
  # 原有vpn_configurations定义保持不变,新增如下展平逻辑
  flattened_tunnels = merge([
    for vpn in local.vpn_configurations : {
      for tunnel in vpn.tunnels : "${vpn.customer_name}-${tunnel.tunnel_name}" => {
        customer_name = vpn.customer_name
        custom_path   = vpn.custom_path
        # 其余VPN级别的字段如果需要可以在此处补充
        tunnel_name   = tunnel.tunnel_name
        left          = tunnel.left
        leftid        = tunnel.leftid
        leftsubnet    = tunnel.leftsubnet
        leftsourceip  = tunnel.leftsourceip
        rightid       = tunnel.rightid
        right         = tunnel.right
        rightsubnet   = tunnel.rightsubnet
        rightsourceip = tunnel.rightsourceip
        ike           = tunnel.ike
        keyexchange   = tunnel.keyexchange
        ikev2         = tunnel.ikev2
        esp           = tunnel.esp
        salifetime    = tunnel.salifetime
        ikelifetime   = tunnel.ikelifetime
        authby        = tunnel.authby
        auto          = tunnel.auto
      }
    }
  ]...)
}

修改模板数据源配置,直接遍历上述展平后的map即可:

data "template_file" "networking_configs" {
  for_each = local.flattened_tunnels
  template = file("${path.module}/template-files/networking-templates/tunnel-configuration.tpl")
  vars = {
    tunnel_name   = each.value.tunnel_name
    left          = each.value.left
    leftid        = module.ipsec.public_ip
    leftsubnet    = each.value.leftsubnet
    leftsourceip  = data.aws_network_interface.eni_ip.private_ip
    rightid       = each.value.rightid
    right         = each.value.right
    rightsubnet   = each.value.rightsubnet
    rightsourceip = each.value.rightsourceip
    ike           = each.value.ike
    keyexchange   = each.value.keyexchange
    ikev2         = each.value.ikev2
    esp           = each.value.esp
    salifetime    = each.value.salifetime
    ikelifetime   = each.value.ikelifetime
    authby        = each.value.authby
    auto          = each.value.auto
  }
}
使用说明
  • 最终每个隧道会生成独立的模板实例,你可以通过data.template_file.networking_configs["{客户名}-{隧道名}"].rendered获取对应隧道的渲染结果
  • 注意:hashicorp/template 提供的template_file数据源已经被官方废弃,如果你使用Terraform 0.12及以上版本,更推荐直接使用内置的templatefile函数实现相同逻辑,不需要额外声明数据源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:18:00