Reputation: 2617
I'm trying to convert a list of items into a map. The element contains a key named tags that contains multiple tags separated by ','
The key should match all nodes that contains the tag.
variable "list" {
type = list(map(string))
default = [
{ a : "a", tags : "k1" },
{ a : "b", tags : "k1" },
{ a : "c", tags : "k1,k2" },
{ a : "d", tags : "k2" },
{ a : "e", tags : "k2" }
]
}
// Output wanted
// {
// "k1" : [{a: a}, {a: b}, {a: c}],
// "k2" : [{a: d}, {a: e}, {a: c}]
// }
I've tried:
[for n in var.list: {for t in split(",", n["tags"]): t => n}]
[
{
"k1" = {a: a}
},
{
"k1" = {a: b}
},
{
"k1" = {a: c},
"k2" = {a: c}
},
{
"k2" = {a: d}
},
{
"k2" = {a: e}
},
]
But I don't know how to merge it after that.
Upvotes: 2
Views: 514
Reputation: 238299
This is a bit trickier. I used two helper data types, helper_list
and helper_map
. The first one check what keys are there, k1
, k2
. The second
creates a list with individual values. The final_map
converts helper_map
into desired map:
locals {
helper_list = distinct(flatten(
[for n in var.list: [for t in split(",", n["tags"]): t]]))
helper_map = flatten([
for k in local.helper_list:
[
for item in var.list:
{"${k}" = {a = item["a"]}} if length(regexall(k, item["tags"])) > 0
]
])
final_map = {for item in local.helper_map: keys(item)[0] => values(item)[0]...}
}
output "test1" {
value = local.final_map
}
Outcome:
est1 = {
"k1" = [
{
"a" = "a"
},
{
"a" = "b"
},
{
"a" = "c"
},
]
"k2" = [
{
"a" = "c"
},
{
"a" = "d"
},
{
"a" = "e"
},
]
}
Upvotes: 1