Reputation: 143
In my terraform code I'd like to merge the following list of maps to one map of maps. The initial list of map looks as follows. Is there a way to do this? If there is not, is it possible to use the original list of maps in a for_each somehow? It only accepts set of strings or maps as far as I know. I tried restructuring it, but no luck.
[
{
"repo1" = {
"description" = "repo1 for something"
"enforce_branch_policies" = true
"name" = "repo1"
}
}
{
"repo2" = {
"description" = "repo2 for something"
"enforce_branch_policies" = true
"name" = "repo2"
}
}
]
Expected map:
{
"repo1" = {
"description" = "repo1 for something"
"enforce_branch_policies" = true
"name" = "repo1"
}
"repo2" = {
"description" = "repo2 for something"
"enforce_branch_policies" = true
"name" = "repo2"
}
}
Upvotes: 2
Views: 5297
Reputation: 4176
You can expand the list with the ...
symbol directly to the merge()
function.
repo_map = merge(local.repo_list...)
Upvotes: 7
Reputation: 28874
This answer assumes a missing ,
in the question between the two maps; otherwise it is a syntax error.
If you want to use this structure in a for_each
meta-argument, then you can note that it is of type list(map(object)))
. We can then use a for
expression to reconstruct into a map(object)
suitable for iteration:
# assumes value is stored in local.repos; modify for your personal config code accordingly
# repo stores the `map(object)` for each element in the list
# the keys and values functions return the keys and values as lists respectively
# the [0] syntax accesses the key and value for each repo map
for_each = { for repo in local.repos : keys(repo)[0] => values(repo)[0] }
This produces the expected value:
{
repo1 = {
description = "repo1 for something"
enforce_branch_policies = true
name = "repo1"
}
repo2 = {
description = "repo2 for something"
enforce_branch_policies = true
name = "repo2"
}
}
While you could also convert the type here from list
to set
with the toset()
function, the return would not be a feasible structure for the for_each
argument value.
Upvotes: 2