Terraform Add new key/value into a existing list of map from another map

Viewed 272

I have following terraform maps

locals {
  accounts = [
    {
      "id" = "111111111111"
      "status" = "ACTIVE"
    },
    {
      "id" = "222222222222"
      "status" = "ACTIVE"
    }
  ]

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

I want to create another list of map from these two variables as below

accounts = [
  {
    "id" = "11111111111"
    "status" = "ACTIVE"
    "type" = "DEV" 
  },
  {
    "id" = "222222222222"
    "status" = "ACTIVE"
    "type" = "PROD"
  }
]

I tried as below. But the problem is it will create lot of duplicates. Can anyone please help me with this.

  account_info = flatten([
    for account in local.accounts : [
      for type in local.account_map : {
        id   = account.id
        type = type
      }
  ]])

1 Answers

You can do that as follows:

 locals {
   
  account_info = [
    for account in local.accounts:
      merge(account, {type = local.account_map[account.id]})
  ]
    
}
Related