问题描述
我正在尝试使用资源google_bigquery_dataset_iam_binding为Bigquery数据集创建IAM绑定。要求是我使用以下结构的变量读取此资源中的参数(dataset_id,角色,成员)-
bq_iam_role_bindings = {
"member1" = {
"dataset1" : ["role1","role2","role5"],"dataset2" : ["role3","role2"],},"member2" = {
"dataset3" : ["role1","role4"],"dataset2" : ["role5"],}
}
因此,我需要遍历此变量并获取在数据集上为每个成员分配的角色。在这里,创建的总资源将为八(对于每个成员,每个数据集和每个角色)。 我是terraform的新手,仅了解如何在资源中对地图应用简单的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
]
}