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

Terraform如何基于两个列表创建嵌套映射并筛选DEV账号

Terraform 筛选索引对应列表生成指定list(map)结构实现

两个按索引一一对应的等长列表,可以直接通过Terraform原生for表达式完成条件筛选,逻辑统一放在locals块中维护即可。

若account_id、account_type是state中其他资源的输出属性,将代码中var.前缀替换为对应资源的引用路径即可。

结构1:条目同时包含id、accounttype字段

遍历列表全量索引,按索引位置匹配对应账号ID和类型,通过if条件仅保留account_type为DEV的条目:

locals {
  dev_accounts = [
    for idx in range(length(var.account_id)) : {
      id          = var.account_id[idx]
      accounttype = var.account_type[idx]
    }
    if var.account_type[idx] == "DEV"
  ]
}

代入给出的示例值,执行terraform plan时输出的dev_accounts结构如下,完全匹配预期:

[
  {
    id          = "111111111111"
    accounttype = "DEV"
  },
  {
    id          = "222222222222"
    accounttype = "DEV"
  }
]

结构2:条目仅包含id字段

仅需修改for表达式返回的map结构,移除accounttype字段即可:

locals {
  dev_accounts = [
    for idx in range(length(var.account_id)) : {
      id = var.account_id[idx]
    }
    if var.account_type[idx] == "DEV"
  ]
}

代入示例值的输出结果:

[
  {
    id = "111111111111"
  },
  {
    id = "222222222222"
  }
]

可选校验规则

为避免两个列表长度不一致导致索引错位、账号和类型匹配错误,可以增加check块做前置校验,在plan阶段直接抛出异常:

check "account_list_length_match" {
  assert = length(var.account_id) == length(var.account_type)
  error_message = "account_id和account_type列表长度必须完全一致,否则会出现匹配错位问题。"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 16:34:46