gpt4 book ai didi

Terraform 生成嵌套数据

转载 作者:行者123 更新时间:2023-12-04 07:53:03 25 4
gpt4 key购买 nike

我在 terraform 中有以下输入,但无法生成所需的输出。
我在 tf 中没有看到任何选项可以在 for 循环中按 resource_app_id 进行过滤。
过去几天一直坚持这个。任何帮助表示赞赏!

input_data = [
{
"resource_app_id" = "62ec2d38-2d53-4204-989b-053a65534873"
"id" = "b43b06f7-92d1-0a98-bcc5-b6d13557fafd"
"Type" = "Role"
},
{
"resource_app_id" = "62ec2d38-2d53-4204-989b-053a65534873"
"id" = "019aa34d-20ce-f301-586c-c5a1cbe410cf"
"type" = "Role"
},
{
"resource_app_id" = "193b6dcb-1323-4f56-8dc5-eed6f9a2789e"
"id" = "c72de1fc-b40d-4bfc-a08a-79a23c486cc7"
"type" = "Role"
},
]

期望输出

requiredResourceAccess": [
{
"resourceAppId": "62ec2d38-2d53-4204-989b-053a65534873",
"resourceAccess": [
{
"id": "b43b06f7-92d1-0a98-bcc5-b6d13557fafd",
"type": "Role"
},
{
"id": "019aa34d-20ce-f301-586c-c5a1cbe410cf",
"type": "Role"
}
]
},
{
"resourceAppId": "193b6dcb-1323-4f56-8dc5-eed6f9a2789e",
"resourceAccess": [
{
"id": "c72de1fc-b40d-4bfc-a08a-79a23c486cc7",
"type": "Role"
}
]
}

最佳答案

是的,我们可以使用 for 循环和 terraform 提供的一些功能来做到这一点:
(不同,展平,如果)

variable "input_data" {
default = [
{
"resource_app_id" : "62ec2d38-2d53-4204-989b-053a65534873",
"id" : "b43b06f7-92d1-0a98-bcc5-b6d13557fafd", "type" : "Role",
},
{
"resource_app_id" : "62ec2d38-2d53-4204-989b-053a65534873",
"id" : "019aa34d-20ce-f301-586c-c5a1cbe410cf", "type" : "Role",
},
{
"resource_app_id" : "193b6dcb-1323-4f56-8dc5-eed6f9a2789e",
"id" : "c72de1fc-b40d-4bfc-a08a-79a23c486cc7", "type" : "Role",
},
]
}

locals {
distinct_resources = distinct(flatten([
for key, value in var.input_data : [
value.resource_app_id
]
]))

output_data = flatten([
for key, value in local.distinct_resources : {
"resourceAppId" = value,
"resourceAccess" : distinct([
for k, v in var.input_data : {
"id" : v.id, "type" : v.type
} if v.resource_app_id == value
])
}
])
}

output "requiredResourceAccess" {
value = local.output_data
}
我压缩了一点输入变量,以便代码更适合屏幕
有了这个,我们可以运行一个计划,我们会得到:
Terraform will perform the following actions:

Plan: 0 to add, 0 to change, 0 to destroy.

Changes to Outputs:
+ requiredResourceAccess = [
+ {
+ resourceAccess = [
+ {
+ id = "b43b06f7-92d1-0a98-bcc5-b6d13557fafd"
+ type = "Role"
},
+ {
+ id = "019aa34d-20ce-f301-586c-c5a1cbe410cf"
+ type = "Role"
},
]
+ resourceAppId = "62ec2d38-2d53-4204-989b-053a65534873"
},
+ {
+ resourceAccess = [
+ {
+ id = "c72de1fc-b40d-4bfc-a08a-79a23c486cc7"
+ type = "Role"
},
]
+ resourceAppId = "193b6dcb-1323-4f56-8dc5-eed6f9a2789e"
},
]

------------------------------------------------------------------------
"terraform_version": "0.14.5" 测试

另外我想指出您的初始输入具有不同大小写的类型:
input_data = [
{ ...
"Type" = "Role"
},
{ ...
"type" = "Role"
},
我假设那是一个错字,并且所有人都应该在同一个案例中,否则会导致错误。

关于Terraform 生成嵌套数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66855052/

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