2

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
      }
  ]])

2 Answers 2

5

You can do that as follows:

 locals {
   
  account_info = [
    for account in local.accounts:
      merge(account, {type = local.account_map[account.id]})
  ]
    
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you could help me with below as this is relatd to the same. That would be really helpful. stackoverflow.com/questions/72773833/…
0

A different way to solve this in my case:

locals {
  map_to_extend = {
    list_one = {
      element_one = "string1"
      element_two = "string2"
    }
    list_two = {
      element_one = "string3"
      element_two = "string4"
    }
  }

  map_to_merge = {
     list_one = true
     list_two = false
  }

  merged_map = {
    for key, value in map_to_extend :
      key => merge(value, { apply_list = local.map_to_merge[key] }
  }

Result:

merged_map = {
    list_one = {
      element_one = "string1"
      element_two = "string2"
      apply_list = true
    }
    list_two = {
      element_one = "string3"
      element_two = "string4"
      apply_list = false
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.