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

如何配置YAML文件以在Terraform中用for_each批量创建Vault实体?

解决Terraform处理YAML配置创建Vault实体的报错问题

问题根源

你现有的config.yaml中,admins和viewers被定义为单个字符串值,但Terraform代码试图将其当作映射/集合类型处理,导致类型不匹配报错。

调整后的config.yaml结构

将admins和viewers改为列表格式,确保yamldecode后解析为Terraform可处理的列表类型:

entities:
  admins:
    - someone@somewhere.com
  viewers:
    - anotherone@somewhere.com

注:即使当前只有一个用户,也保持列表结构,后续添加用户只需追加- 新邮箱即可,无需修改Terraform代码逻辑。

对应修改Terraform代码

更新locals块,直接将列表转换为集合适配for_each要求:

locals {
  config = yamldecode(file("config.yaml"))
  admins = toset(local.config["entities"]["admins"])
  viewers = toset(local.config["entities"]["viewers"])
}

resource "vault_identity_entity" "admins" {
  for_each  = local.admins

  name      = each.key
  policies  = ["test"]
  metadata  = {
    foo = "bar"
  }
}

resource "vault_identity_entity" "viewers" {
  for_each  = local.viewers

  name      = each.key
  policies  = ["test"]
  metadata  = {
    foo = "bar"
  }
}

错误说明

原YAML中admins: someone@somewhere.com会被解析为字符串类型,而keys()函数要求输入为映射类型,...展开操作仅支持列表/元组/集合类型,因此触发报错。改成列表结构后,直接通过toset()转换为集合,完美适配for_each对集合类型的依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:50:32