Home > database >  I want to merge duplicated key map in Terraform
I want to merge duplicated key map in Terraform

Time:12-20

local.tf

locals{
  sample_map = [
    {"aaa":"111"},
    {"bbb":"222"},
    {"aaa":"333"},
    {"bbb":"444"},
  ]
}

I want to merge values of this sample map as a list format based on the same key. So the form that I want to make is like below.

sample_map_result = {
  "aaa": ["111","333"]
  "bbb": ["222","444"]
}

Thank you for your help in advance.

I made this code, but i dont know the next step.

sample_map_result = flatten([
  for mp in local.sample_map: flatten([
    for k, v in mp: {
      
    }
  ])
])

CodePudding user response:

Where is a solution for this

from collections import defaultdict

sample_map_result = defaultdict(list)

for mp in local.sample_map:
  for k, v in mp.items():
    sample_map_result[k].append(v)

sample_map_result = dict(sample_map_result)

CodePudding user response:

Your initial example is not valid because it isn't actually possible to construct a map with duplicate keys as you've shown here. It's a fundamental part of the behavior of maps that each key can exist only once.

The most straightforward answer would be to write out the map directly in the form you want, as a map of lists or a map of sets:

sample_map_result = tomap({
  aaa = toset(["111","333"])
  bbb = toset(["222","444"])
})

If having each pair as a separate value is an important requirement then you'll need to decide some other way to represent those pairs. For example, you could write the source data as a set of tuples:

locals {
  sample_items = toset([
    ["aaa", "111"],
    ["bbb", "222"],
    ["aaa", "333"],
    ["bbb", "444"],
  ])
}

You could then project that into a map of lists using a for expression using the ... grouping mode:

locals {
  result = tomap({
    for pair in local.sample_items : pair[0] => pair[1]...
  })
}

The ... symbol after the value expression (pair[1]) tells Terraform that you intend to group values by the result of the key expression (pair[0]).

This general pattern can work for any source collection that has one element per pair of key and value. You'd just need to write appropriate expressions before and after the => symbol to tell Terraform how to find the key and value (respectively) for each of the input elements.

  • Related