gpt4 book ai didi

json - Terraform:如何通过 json 文件迭代 map 输入的键值对

转载 作者:行者123 更新时间:2023-12-02 19:12:00 27 4
gpt4 key购买 nike

这是我的输入 json 文件:

{
"inputs": [
{
"acct_id": "foo-bar-15",
"display_name": "foo bar",
"project-role-pairs": {"test-1234": "roles/logging.logWriter", "test-2345": "roles/storage.objectViewer"}
},
{
"acct_id": "foo-bar-16",
"display_name": "john doe",
"project-role-pairs": {"test-3456": "roles/logging.logWriter", "test-4567": "roles/storage.objectViewer"}
}
]
}

代码:这是我的代码,它根据输入在 GCP 中创建服务帐户(该部分工作正常)。它还尝试根据上面 json 文件中的 project-roles-pairs 映射在 2 个项目中创建 IAM 角色。我无法通过 map 进行交互。我就是不知道为什么。目前的代码只是使用映射中的第一个键来表示两者,就好像没有第二对键值一样。我一直在寻找“扁平化”和动态 block 和集合产品。它们似乎不适合用例,或者我无法有效地使用它们。请帮忙。

locals {
json_data_7 = jsondecode(file("./data7.json"))
}


# Creates a Service Account for each top level in input
resource "google_service_account" "service_accounts_for_each_7" {
for_each = {for v in local.json_data_7.inputs: v.acct_id => v.display_name}
account_id = each.key
display_name = each.value
}

#
resource "google_project_iam_member" "rolebinding" {
for_each = { for v in local.json_data_7.inputs: v.acct_id => v }
project = element(keys(each.value.project-role-pairs),0) #ONLYfirst key in MAP , not what I want, I would like this part loop through map and create a role for each KV-pair in JSON input
role = lookup(each.value.project-role-pairs,element(keys(each.value.project-role-pairs),0))
member = "serviceAccount:${google_service_account.service_accounts_for_each_7[each.key].email}"
}

问题:

如何让我的代码迭代 JSON 文件中的 project-roles-pairs 输入的 2 个键值对?谢谢。

最佳答案

如果我理解正确,您需要对输入项目角色对迭代两次。因此,您可以首先创建一个helper_list,如下所示:

locals {

helper_list = flatten([ for v in local.json_data_7.inputs:
[ for project, role in v.project-role-pairs:
{ "project" = project
"role" = role
acct_id = v.acct_id
display_name = v.display_name}
]
])
}

以上将导致 helper_list 为:

[
{
"acct_id" = "foo-bar-15"
"display_name" = "foo bar"
"project" = "test-1234"
"role" = "roles/logging.logWriter"
},
{
"acct_id" = "foo-bar-15"
"display_name" = "foo bar"
"project" = "test-2345"
"role" = "roles/storage.objectViewer"
},
{
"acct_id" = "foo-bar-16"
"display_name" = "john doe"
"project" = "test-3456"
"role" = "roles/logging.logWriter"
},
{
"acct_id" = "foo-bar-16"
"display_name" = "john doe"
"project" = "test-4567"
"role" = "roles/storage.objectViewer"
},
]

随后,您的 google_project_iam_member 可能是:

resource "google_project_iam_member" "rolebinding" {
for_each = { for idx, v in local.helper_list: idx => v }
project = each.value.project
role = each.value.role
member = "serviceAccount:${google_service_account.service_accounts_for_each_7[each.value.acct_id].email}"
}

请注意,上述内容可能需要调整,因为我通常不使用 GCP,因此我无法验证 google_project_iam_member 到底应该是什么样子。

关于json - Terraform:如何通过 json 文件迭代 map 输入的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64164785/

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