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

如何在Terraform中合并字符串列表与映射列表生成动态结构

解决方案

要实现每个集群对应全部节点池配置的动态结构,核心是生成集群与节点池的笛卡尔积,替代仅能一一对应的zipmap。以下是具体实现方式:

Terraform 示例实现

假设mapA是类似这样的节点池配置列表(每个元素是节点池的映射):

locals {
  listA = ["cluster-0", "cluster-1"]
  mapA = [
    {name = "pool-0", size = 2},
    {name = "pool-1", size = 3},
    {name = "pool-2", size = 1}
  ]
}

通过嵌套for循环生成目标结构listB:

locals {
  listB = flatten([
    for cluster in local.listA : [
      for pool in local.mapA : {
        cluster_name = cluster
        node_pool    = pool
      }
    ]
  ])
}

说明

  • 外层for循环遍历每个集群,内层for循环遍历所有节点池,组合成每个集群+节点池的配对结构
  • 使用flatten将嵌套列表展开为一维列表,得到最终的listB

最终listB的结构示例:

[
  {cluster_name = "cluster-0", node_pool = {name = "pool-0", size = 2}},
  {cluster_name = "cluster-0", node_pool = {name = "pool-1", size = 3}},
  {cluster_name = "cluster-0", node_pool = {name = "pool-2", size = 1}},
  {cluster_name = "cluster-1", node_pool = {name = "pool-0", size = 2}},
  {cluster_name = "cluster-1", node_pool = {name = "pool-1", size = 3}},
  {cluster_name = "cluster-1", node_pool = {name = "pool-2", size = 1}}
]

如果需要以集群为键、对应全部节点池的映射结构,可调整为:

locals {
  listB = {
    for cluster in local.listA : cluster => local.mapA
  }
}

这种结构下,listB会是一个映射集合,每个集群键对应完整的节点池列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:42:42