Richard Brown
Richard Brown

Reputation: 1

Terraform converting list records into a list of maps

I am struggling to take the output from a Terraform function (a list block) and convert it into a list of maps, I am trying to convert

The following:

mylist = [
  {
    key       = "mykey1"
    property1 = "mykey1property1"
    property2 = "mykey1property2"
  },
  {
    key       = "mykey2"
    property1 = "mykey2property1"
    property2 = "mykey2property2"
  }
]

into:

mylistmap = {
  mykey1 = {
    property1 = "mykey1property1"
    property2 = "mykey1property2"
  }

  mykey2 = {
    property1 = "mykey2property1"
    property2 = "mykey2property2"
  }
}

I think zipmap is what I need but I cant find any decent examples to do this.

Upvotes: 0

Views: 174

Answers (1)

Marko E
Marko E

Reputation: 18148

Not sure if this is the best way possible, but with some manipulation with keys and values I was able to achieve what you want:

locals {
  mylist = [
    {
      key       = "mykey1"
      property1 = "mykey1property1"
      property2 = "mykey1property2"
    },
    {
      key       = "mykey2"
      property1 = "mykey2property1"
      property2 = "mykey2property2"
   }
  ]

  mylistmap = { for i in local.mylist: i.key => {
     for k,v in i: k => v if k != "key"
    } 
  }
}

Using terraform console, this yields the following values:

> local.mylistmap
{
  "mykey1" = {
    "property1" = "mykey1property1"
    "property2" = "mykey1property2"
  }
  "mykey2" = {
    "property1" = "mykey2property1"
    "property2" = "mykey2property2"
  }
}

Upvotes: 2

Related Questions