hlesnt395
hlesnt395

Reputation: 803

Terraform dynamically create a list(map)

I have following account_map.

account_map   = {
      111111111111 = "DEV"
      222222222222 = "DEV"
      333333333333 = "STG"
      444444444444 = "DEV"
      555555555555 = "PROD"
      666666666666 = "DEV"

    }

I'm trying something like below to get a list(map) output for my instance_data variable. (It should return only the account IDs of the DEV). I know lookup is not going to work here. I pasted it, because this is my last try out.

locals {
  instance_data = flatten([
    for account in module.organization.organization_accounts : [
      for dev_accounts in lookup(local.account_group, account.id) : {
        id = dev_accounts
      }
    ]
  ])

So my local.instance_data variable output must be something like below

  + instance_data = [
      + {
          + id = "111111111111"
        },
      + {
          + id = "222222222222"
        },
      + {
          + id = "444444444444"
        },
      + {
          + id = "666666666666"
]

Upvotes: 0

Views: 465

Answers (1)

Marcin
Marcin

Reputation: 238081

You can reverse the keys and values from your map:

locals {

  account_map   = {
      111111111111 = "DEV"
      222222222222 = "DEV"
      333333333333 = "STG"
      444444444444 = "DEV"
      555555555555 = "PROD"
      666666666666 = "DEV"
    }

  env_map = {for k, v in local.account_map: v => k...}
}

then you get "DEV" accounts ids as:

dev_account_ids = env_map["DEV"]

UPDATE

To get exactly your desired output, you can do:

  env_map = [for k, v in local.account_map: {
               id = k 
            } if v == "DEV"
            ]

Upvotes: 2

Related Questions