David
David

Reputation: 500

Terraform : merge list of maps and concatenate their value from duplicate keys

I want to concatenate the values of a list of maps that share the same key. I have a list of maps that looks like this:

tags = [
  {
    key = "env"
    value = "dev"
  },
  {
    key = "project"
    value = "tata"
  },
  {
    key = "env"
    value = "prod"
  },
  {
    key = "project"
    value = "tata"
  },
  {
    key = "project"
    value = "titi"
  }
]

And I would like to convert it in the following way.

tags = [
  {
    key = "env"
    value = ["dev", "prod"]
  },
  {
    key = "project"
    value = ["tata", "titi"]
  }
]

Or better yet, like this:

tags = {
    env = ["dev", "prod"]
    project = ["tata", "titi"]
  }

This post looks like my problem, but I couldn't adapt it to my case.

Thanks for your help.

Upvotes: 6

Views: 5735

Answers (1)

Marcin
Marcin

Reputation: 238081

You can do this as follows:

variable "tags" {

  default = [
  {
    key = "env"
    value = "dev"
  },
  {
    key = "project"
    value = "tata"
  },
  {
    key = "env"
    value = "prod"
  },
  {
    key = "project"
    value = "tata"
  },
  {
    key = "project"
    value = "titi"
  }
]


}

locals {

  keys_available = distinct([for tag in var.tags: tag["key"]])
  
  # with duplicate values
  helper_map = merge([for key in local.keys_available:
                  {for tag in var.tags:
                     key => tag["value"]... if tag["key"] == key
                  }  
               ]...)
  # duplicates removed  
  final_map = {for k,v in local.helper_map: k => distinct(v)}
}

output "test" {
  value = local.final_map
}

Gives:

test = {
  "env" = tolist([
    "dev",
    "prod",
  ])
  "project" = tolist([
    "tata",
    "titi",
  ])
}

Upvotes: 6

Related Questions