hlesnt395
hlesnt395

Reputation: 803

Terraform construct a list from map

I have a terraform map like below.

org_sub_accounts = [
  {
    "id" = "11111111111"
    "type" = "test"
  },
  {
    "id" = "22222222222"
    "type" = "prod"
  },
  {
    "id" = "33333333333"
    "type" = "prod"
  }
 ]

I want to create a list from this map by including the account id where the type is prod. So the output should be something like the below.

prod_accounts = ["22222222222","33333333333"]

Can someone please help? Was trying to figure this out for some time now.

Upvotes: 0

Views: 2190

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28854

Assuming that org_sub_accounts is defined as a local (modify answer accordingly if otherwise), then this can be constructed from a for expression lambda inside the list constructor:

[for account in local.org_sub_accounts : account.id if account.type == "prod"]

which returns the value:

[
  "22222222222",
  "33333333333",
]

which can be assigned to a prod_accounts as desired. Note this assumes your original structure is a list(object) as shown in the question, and therefore always contains the keys id and type.

Upvotes: 4

Related Questions