T Anna
T Anna

Reputation: 1004

Terraform iterate over a map of maps

My input is as below:

list_groups= [
      {
           "dev-api-eu" = {
              envs  = [
                   "dev-eu-1",
                   "dev-eu-2",
                ]
             hosts = [
                   "dev-api-eu1",
                   "dev-api-eu2",
                ]
            }
           "dev-api-uk" = {
               envs  = [
                   "dev-uk-1",
                   "dev-uk-2",
                ]
               hosts = [
                   "dev-api-uk1",
                   "dev-api-uk2",
                ]
            }
        },
       {
           "dev-api-us" = {
               envs  = [
                   "dev-us-1",
                   "dev-us-2",
                ]
               hosts = [
                   "dev-api-us1",
                   "dev-api-us2",
                ]
            }
        },
    ]

Now I want my output as a map of 3 maps with 3 keys :

"dev-api-eu"
"dev-api-uk"
"dev-api-us"

With no changes to the values.

Below is my desired Output:

 map_groups1      = {
       dev-api-eu = {
           envs  = [
               "dev-eu-1",
               "dev-eu-2",
            ]
           hosts = [
               "dev-api-eu1",
               "dev-api-eu2",
            ]
        }
       dev-api-uk = {
           envs  = [
               "dev-uk-1",
               "dev-uk-2",
            ]
           hosts = [
               "dev-api-uk1",
               "dev-api-uk2",
            ]
        }
       dev-api-us = {
           envs  = [
               "dev-us-1",
               "dev-us-2",
            ]
           hosts = [
               "dev-api-us1",
               "dev-api-us2",
            ]
        }
    }

Below works if each item in the list has just one map

map_groups1 = {
for record in local.list_groups:
  keys(record)[0] => values(record)[0]
}

The above code skips the key "dev-api-uk" and just gives two maps in the result. But, as you can see, my first item in the input list has two maps and there can be n no of maps. Any ideas?

Upvotes: 3

Views: 627

Answers (1)

Marcin
Marcin

Reputation: 238081

You can just use merge with expantion:

output "test" {  
    value = merge(var.list_groups...)
}

Upvotes: 1

Related Questions