XciD
XciD

Reputation: 2617

Convert a list to map and with counted key in terraform

I'm trying to convert a list of items into a map.

The key should match a key in the item and increment on each element with the same key.

Maybe an example will be more understable

variable "list" {
  type = list(map(string))
  default = [
    { a : "a", k : "node" },
    { a : "b", k : "node" },
    { a : "c", k : "master" },
    { a : "d", k : "master" }
  ]
}
    
// Output wanted
// {
//  "node-0" : {a: a},
//  "node-1" : {a: b},
//  "master-0" : {a: c},
//  "master-1" : {a: d}
// }

Thanks

Upvotes: 2

Views: 1163

Answers (1)

Marcin
Marcin

Reputation: 238687

I prepared, not-so-pretty way of achieving this. Maybe with more time could find much nicer solution, but at least it could be considered as a first step towards one.

The idea is to create a helper_map, same as in your earlier question. From that through a bit of manipulation of the keys and values, the outcome can be achieved.

variable "list" {
  type = list(map(string))
  default = [
    { a : "a", k : "node" },
    { a : "b", k : "node" },
    { a : "c", k : "master" },
    { a : "d", k : "master" }
  ]
}

locals {

  helper_map = {for idx,item in var.list: item["k"] => {a = item["a"]}...}
  
  final_map  = {for v1 in flatten([
                  for key, item in local.helper_map: [
                    for idx, val in item:  {
                      "${key}-${idx}" = val
                    }  
                  ]  
                ]): keys(v1)[0] => values(v1)[0]}  
}


output "test2" {
  value = local.final_map
}

Outcome:

test2 = {
  "master-0" = {
    "a" = "c"
  }
  "master-1" = {
    "a" = "d"
  }
  "node-0" = {
    "a" = "a"
  }
  "node-1" = {
    "a" = "b"
  }
}

Upvotes: 4

Related Questions