问题描述
我正在尝试在其他资源中为for_each循环创建局部变量,但无法按预期制作局部映射。
以下是我尝试过的。 (terraform 0.12)
预计要循环的地图
temple_list = { "test2-role" = "test-test2-role",... }
main.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(),但似乎对我不起作用。 (而且我不确定为什么会创建空的。)
解决方法
您可以分两个步骤进行操作:
- 将其转换为过滤后的对象列表:
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"
},]
- 然后使用
for
轻松将其转换为地图:
my_map = { for item in local.result: item.key => item.value }
给出:
{
"test2-role" = "test-test2-role"
}