我正在尝试转换map(object)
,但是当涉及到更复杂的循环用例时,我觉得Terraform文档有点缺乏。
有人能写一个for循环,使output.solution
等于local.desired_output
吗?
locals {
users = {
user1 = {
teams = {
team1 = "member"
team2 = "admin"
}
}
user2 = {
teams = {
team1 = "member"
}
}
}
desired_output = {
user1_team1 = {
user = "user1"
team = "team1"
role = "member"
}
user1_team2 = {
user = "user1"
team = "team2"
role = "admin"
}
user2_team1 = {
user = "user2"
team = "team1"
role = "member"
}
}
}
output "solution" {
value = ???
}
编辑:
找到了解决方案,但是很丑:
locals {
temp_output = flatten([
for user, data in local.users : [
for team, role in data.teams : {
join("-", [user, team]) = {
"user" = user
"team" = team
"role" = role
}
}
]
])
}
output "solution" {
value = {
for tuple in local.temp_output : keys(tuple)[0] => values(tuple)[0]
}
}
有人可以建议一种更清洁的方法吗?
编辑2:
在马丁·阿特金斯(Martin Atkins)的评论中,清洁度是主观的: 我对解决方案不满意的是,它需要将循环包装在各种括号中,然后使用另一个循环将其拆包。我想做的是直接从嵌套循环创建所需的输出,而无需执行创建元组列表的中间步骤。
如果可以的话,这样的事情会更清洁:
# Does not work
output = {
for user, data in local.users :
for team, role in data.teams :
join("-", [user, team]) => {
"user" = user
"team" = team
"role" = role
}
}
我不完全理解上述原因为何不起作用;似乎您无法进行嵌套循环,除非内部循环包含在[]
或{}
中,然后需要更多代码才能展开,以达到for_each
友好的状态对象结构。