hlesnt395
hlesnt395

Reputation: 803

Convert Terraform map keys into a list

I have a Terraform map of accounts like below.

 account_map  = {
      111111111111 = "DEV"
      222222222222 = "DEV"
      333333333333 = "STG"
      333333333333 = "PROD"
 }

How can I create a list of Dev accounts IDs as below from the above map?. I tired to use keys function but not sure how to search the DEV value inside the keys function.

dev_accounts = ["111111111111", "222222222222"]

Upvotes: 6

Views: 7148

Answers (2)

Viacheslav Subotskiy
Viacheslav Subotskiy

Reputation: 31

There is a built-in Terraform keys function.

> keys({a=1, c=2, d=3})
[
  "a",
  "c",
  "d",
]

So, in your case:

locals {
  account_map = {
    111111111111 = "DEV"
    222222222222 = "DEV"
    333333333333 = "STG"
    333333333333 = "PROD"
  }
  dev_accounts = keys(local.account_map)
}

output "dev_accounts" {
  value = local.dev_accounts
}

Results to:

% terraform plan

Changes to Outputs:
  + dev_accounts = [
    + "111111111111",
    + "222222222222",
    + "333333333333",
  ]
...

Terraform docs: https://developer.hashicorp.com/terraform/language/functions/keys

Upvotes: 3

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

For situations like this without an intrinsic function, and no possibility of a custom function, then you basically must use a for expression:

local {
  dev_accounts = [ for number, account in var.account_map : number if account == "DEV" ] # ["111111111111", "222222222222"]
}

Upvotes: 5

Related Questions