gpt4 book ai didi

Terraform - 迭代嵌套 map

转载 作者:行者123 更新时间:2023-12-04 02:32:25 44 4
gpt4 key购买 nike

我正在尝试使用资源 google_bigquery_dataset_iam_binding 为 Bigquery 数据集创建 IAM 绑定(bind)。要求是我使用以下结构的变量读取此资源中的参数(dataset_id、角色、成员) -

  bq_iam_role_bindings = {
"member1" = {
"dataset1" : ["role1","role2", "role5"],
"dataset2" : ["role3","role2"],
},
"member2" = {
"dataset3" : ["role1","role4"],
"dataset2" : ["role5"],
}
}
因此,我需要遍历这个变量并获取在数据集上为每个成员分配的角色。这里创建的总资源为 8 个(对于每个成员、每个数据集和每个角色)。
我是 terraform 的新手,只了解如何在 map 上应用简单的 for 循环和在资源中应用 for_each 循环。想了解我想要做的事情怎么可能。
这是我发现的最接近的 - Map within a map in terraform variables我可以在嵌套映射中读取值,但在我的情况下我也需要提取键。
任何人都可以在这里帮忙。

最佳答案

您可以将其重新组织为更多 for_each友好的对象列表并将其存储在本地 helper_list .
例如:

variable "bq_iam_role_bindings" {

default = {
"member1" = {
"dataset1" : ["role1","role2", "role5"],
"dataset2" : ["role3","role2"],
},
"member2" = {
"dataset3" : ["role1","role4"],
"dataset2" : ["role5"],
}
}
}

locals {

helper_list = flatten([for member, value in var.bq_iam_role_bindings:
flatten([for dataset, roles in value:
[for role in roles:
{"member" = member
"dataset" = dataset
"role" = role}
]])
])
}
这将导致 helper_list形式为:
[
{
"dataset" = "dataset1"
"member" = "member1"
"role" = "role1"
},
{
"dataset" = "dataset1"
"member" = "member1"
"role" = "role2"
},
{
"dataset" = "dataset1"
"member" = "member1"
"role" = "role5"
},
{
"dataset" = "dataset2"
"member" = "member1"
"role" = "role3"
},
{
"dataset" = "dataset2"
"member" = "member1"
"role" = "role2"
},
{
"dataset" = "dataset2"
"member" = "member2"
"role" = "role5"
},
{
"dataset" = "dataset3"
"member" = "member2"
"role" = "role1"
},
{
"dataset" = "dataset3"
"member" = "member2"
"role" = "role4"
},
]
上面的表格更容易使用 for_each ,例如:
resource "google_bigquery_dataset_iam_binding" "reader" {

for_each = { for idx, record in local.helper_list : idx => record }

dataset_id = each.value.dataset
role = each.value.role

members = [
each.value.member
]
}

关于Terraform - 迭代嵌套 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63500554/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com