Reputation: 2605
I'm trying to convert a list of items into a map. The key will match a key in the item and the value should create a list of appends to the list if the key already exist.
Maybe an example will be more understable
variable "list" {
type = list(map(string))
default = [
{ a : "a", k : "k1" },
{ a : "b", k : "k1" },
{ a : "c", k : "k1" },
{ a : "d", k : "k2" },
{ a : "e", k : "k2" }
]
}
// Output wanted
// {
// "k1" : [{a: "a"}, {a: "b"}, {a: "c"}],
// "k2" : [{a: "d"}, {a: "e"}]
// }
Thank you
Upvotes: 3
Views: 3575
Reputation: 238975
You can have a look at the following:
variable "list" {
type = list(map(string))
default = [
{ a : "a", k : "k1" },
{ a : "b", k : "k1" },
{ a : "c", k : "k1" },
{ a : "d", k : "k2" },
{ a : "e", k : "k2" }
]
}
output "test" {
value = {for item in var.list:
item["k"] => {a = item["a"]}...
}
}
The above code uses three dots operator and it produces:
test = {
"k1" = [
{
"a" = "a"
},
{
"a" = "b"
},
{
"a" = "c"
},
]
"k2" = [
{
"a" = "d"
},
{
"a" = "e"
},
]
}
Upvotes: 4