Here is my issue - I have a locals code block like the below. I need to create a Map from these values (these values are used in multiple places)
locals {
object = {
1 = {
name = "val1"
keys = ["val1"]
}
2 = {
name = "val2"
keys = ["val2", "val3", "val4"]
}
}
associations = flatten(
[
for obj in local.object : [
for association_key in obj.keys : {
"${obj.name}-${association_key}" = {
key = obj.name
association_key = association_key
}
}
]
]
)
}
Which when I run a terraform plan outputting the above - I get:
testing = [
+ {
+ val1-val1 = {
+ association_key = "val1"
+ key = "val1"
}
},
+ {
+ val2-val2 = {
+ association_key = "val2"
+ key = "val2"
}
},
+ {
+ val2-val3 = {
+ association_key = "val3"
+ key = "val2"
}
},
+ {
+ val2-val4 = {
+ association_key = "val4"
+ key = "val2"
}
},
]
What I need to get however looks like this:
testing = [
+ val1-val1 = {
+ association_key = "val1"
+ key = "val1"
}
+ val2-val2 = {
+ association_key = "val2"
+ key = "val2"
}
+ val2-val3 = {
+ association_key = "val3"
+ key = "val2"
}
+ val2-val4 = {
+ association_key = "val4"
+ key = "val2"
}
]
The reason for this is that there are many repetitions in keys value from object and there needs to be a unique value in the map.
I have attempted the solution Here - but I have not been able to create the Map that I need.
If you have a list of maps and all of the keys across all of the maps are unique, you can use merge
to combine them all into a single map with all of those keys represented.
For example:
merge(local.associations...)
The ...
here tells Terraform that it should treat each element of local.associations
as a separate argument to merge
. Without that suffix Terraform would instead treat the entire list as just a single argument to merge
, which would not work because merge
expects all of its arguments to be maps.
This follows the same approach as one of the examples that is included in the documentation for merge
at the time I'm writing this answer:
The following example uses the expansion symbol (
...
) to transform the value into separate arguments. Refer to Expanding Function Argument for details.> merge([{a="b", c="d"}, {}, {e="f", c="z"}]...) { "a" = "b" "c" = "z" "e" = "f" }