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

如何在Terraform中遍历嵌套YAML配置创建Vault身份实体

解决Terraform解析YAML创建Vault身份实体的问题

步骤1:加载并解析YAML配置

先把你的YAML配置加载到Terraform中,推荐将配置保存为本地文件(比如config.yaml),再用yamldecode函数解析:

locals {
  config = yamldecode(file("${path.module}/config.yaml"))
}

如果不想单独存文件,也可以直接把YAML内容嵌入代码:

locals {
  config = yamldecode(<<EOF
config:
  groups:
    group1:
      capabilities:
        - create
        - read
        - update
      members:
      - robert@gmail.com
      - paul@gmail.com
    group2:
      capabilities:
        - create
        - list
      members:
        - peter@gmail.com
    group3:
      capabilities:
        - read
        - list
      members:
        - john@gmail.com
EOF)
}

步骤2:提取并去重所有成员邮箱

通过flatten展开所有组的成员列表,再用distinct去除重复邮箱(避免同一个邮箱被重复创建实体):

locals {
  all_members = distinct(flatten([for group in local.config.groups : group.members]))
}

步骤3:配置for_each遍历创建资源

把整理好的成员列表转换为for_each支持的映射格式,遍历创建Vault身份实体:

resource "vault_identity_entity" "this" {
  for_each = { for email in local.all_members : email => email }

  name = each.value
}

完整整合代码

locals {
  config = yamldecode(file("${path.module}/config.yaml"))
  all_members = distinct(flatten([for group in local.config.groups : group.members]))
}

resource "vault_identity_entity" "this" {
  for_each = { for email in local.all_members : email => email }

  name = each.value
}

这样就能自动遍历YAML中所有组的成员,为每个邮箱创建对应的Vault身份实体,同时自动处理重复邮箱的情况,避免资源冲突。

内容的提问来源于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 12:20:35