gpt4 book ai didi

Terraform:合并列表映射并合并来自重复键的列表

转载 作者:行者123 更新时间:2023-12-04 09:48:24 25 4
gpt4 key购买 nike

我有这样的东西

locals {
roles = [
{
role = "roles/admin"
members = ["user:user@example.com"]
},
{
role = "roles/viewer"
members = ["user:user2@example.com"]
}
]
}

我希望我的模块能够导出它们自己的角色列表,例如

roles = [
{
role = "roles/viewer"
members = ["user:newperson@example.com"]
}
]

然后能够将这些东西合并在一起得到

locals {
roles = [
{
role = "roles/admin"
members = ["user:user@example.com"]
},
{
role = "roles/viewer"
members = ["user:user2@example.com", "user:newperson@example.com"]
}
]
}

我知道如果我将所有内容都存储为 map ,我可以合并这些 map ,只要没有重复的键,它就可以正常工作。但在这种情况下,我明确希望能够拥有重复的键,这样一个模块就不需要关心任何其他模块。

更新 我可以通过这样做来实现这一点:

roles = distinct(flatten([
for rm in local.role_maps : [
for role, members in rm :
{
role = role
members = sort(distinct(flatten([
for m in local.role_maps :
m[role] if lookup(m, role, null) != null
])))
}
]
]))

最佳答案

这似乎是一个很好的应用 for expression使用 ... 分组修饰符,它可以通过按键分组生成列表映射。

variable "custom_roles" {
type = list(object({
role = string
members = list(string)
})
}

locals {
default_roles = [
{
role = "roles/admin"
members = ["user:user@example.com"]
},
{
role = "roles/viewer"
members = ["user:user2@example.com"]
}
]
all_roles = concat(
local.default_roles,
var.custom_roles,
)

# First we'll project the inputs so that we have one
# role/member pair per element.
flat_roles = flatten([
for r in locals.all_roles : [
for m in r.members : {
role = r.role
member = m
}
]
])

# Then we can use that flattened list to produce a map
# grouped by unique role key.
merged_roles = {
for k, v in local.all_roles : k => v...
}

# Finally, if the list-of-objects representation was
# important then we can recover it by projecting that
# merged_roles map back into the list shape.
merged_roles_list = tolist([
for role, members in local.merged_roles : {
role = role
members = tolist(members)
}
])
}

在上面,local.merged_roles 是一个列表映射,如下所示:

{
"roles/admin" = ["user:user@example.com"]
"roles/viewer" = ["user:user2@example.com", "user:newperson@example.com"]
}

您可以直接使用该 map ,但以防万一对象列表形式很重要,我包含了 local.merged_roles_list,它应该与您提出问题的结构相匹配。

关于Terraform:合并列表映射并合并来自重复键的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62049580/

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