gpt4 book ai didi

要通过删除空对象进行映射的 Terraform 元组?

转载 作者:行者123 更新时间:2023-12-01 23:48:53 28 4
gpt4 key购买 nike

我正在尝试为其他资源中的 for_each 循环创建局部变量,但无法按预期制作局部映射。

以下是我试过的。 (地形 0.12)

预期映射到循环

temple_list = { "test2-role" = "test-test2-role", ... }

ma​​in.tf

locals {
tmpl_list = flatten([
for role in keys(var.roles) : {
for tmpl_vars in values(var.roles[role].tmpl_vars) :
role => "test-${role}" if tmpl_vars == "SECRET"
}
])
}

output "tmpl_list" {
value = local.tmpl_list
}

variable "roles" {
type = map(object({
tmpl_vars = map(string)
tags = map(string)
}))

default = {
"test-role" = {
tmpl_vars = {test = "y"}
tags = { test = "xxx"}
}
"test2-role" = {
tmpl_vars = { token = "SECRET" }
tags = {}
}
"test3-role" = {
tmpl_vars = {test = "x"}
tags = {}
}
}
}

错误来自合并

    | var.roles is map of object with 3 elements

Call to function "merge" failed: arguments must be maps or objects, got
"tuple".

没有合并

locals {
tmpl_list = flatten([
for role in keys(var.roles) : {
for tmpl_vars in values(var.roles[role].tmpl_vars) :
role => "test-${role}" if tmpl_vars == "SECRET"
}
])
}

output "tmpl_list" {
value = local.tmpl_list
}

variable "roles" {
type = map(object({
tmpl_vars = map(string)
tags = map(string)
}))

default = {
"test-role" = {
tmpl_vars = {test = "y"}
tags = { test = "xxx"}
}
"test2-role" = {
tmpl_vars = { token = "SECRET" }
tags = {}
}
"test3-role" = {
tmpl_vars = {test = "x"}
tags = {}
}
}
}

没有合并的结果

tmpl_list = [
{},
{
"test2-role" = "test-test2-role"
},
{},
]

我尝试了其他函数,例如 tomap(),但它似乎对我不起作用。(我也不确定为什么会创建空的。)

如何将这个元组转换为没有空元组的映射?

最佳答案

您可以分两步完成:

  1. 将其转换为过滤后的对象列表:
locals {  
result = flatten([
for role, role_value in var.roles: [
for tmpl_vars in role_value.tmpl_vars: {
key = role
value = "test-${role}"
} if tmpl_vars == "SECRET"
]
])
}

local.result 将具有以下值:

[
{
"key" = "test2-role"
"value" = "test-test2-role"
},
]
  1. 然后很容易用for把它转换成 map :
my_map = { for item in local.result: item.key => item.value }

给出:

{
"test2-role" = "test-test2-role"
}

关于要通过删除空对象进行映射的 Terraform 元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63728834/

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