简体   繁体   中英

Terraform: Convert a list of maps into a revised list of maps

My input is:

input = [
  {
    x = "X1"
    y = "Y1"
  },
  {
    x = "X2"
    y = "Y2"
  },
  {
    x = "X3"
    y = "Y3"
  },
]

My desired output is:

output = [
  {
    val         = "X1",
    description = "This is a value of X"
  },
  {
    val         = "Y1",
    description = "This is a value of Y"
  },
  {
    val         = "X2",
    description = "This is a value of X"
  },
  {
    val         = "Y2",
    description = "This is a value of Y"
  },
  {
    val         = "X3",
    description = "This is a value of X"
  },
  {
    val         = "Y3",
    description = "This is a value of Y"
  },
]

How can this be achieved in Terraform?

I was able to use the flatten() function in terraform for this:

flatten([
  for a_map in var.input : [
    { val = a_map.x, description = "This is a value of X" },
    { val = a_map.y, description = "This is a value of Y" },
  ]
])

An advantage of this approach is that it will maintain the order of values.

So the output will be:

[
  {
    "description" = "This is a value of X"
    "val" = "X1"
  },
  {
    "description" = "This is a value of Y"
    "val" = "Y1"
  },
  {
    "description" = "This is a value of X"
    "val" = "X2"
  },
  {
    "description" = "This is a value of Y"
    "val" = "Y2"
  },
  {
    "description" = "This is a value of X"
    "val" = "X3"
  },
  {
    "description" = "This is a value of Y"
    "val" = "Y3"
  },
]

The following produces such output:



variable "input" {

  default = [
    {
      x = "X1"
      y = "Y1"
    },
    {
      x = "X2"
      y = "Y2"
    },
    {
      x = "X3"
      y = "Y3"
    },
  ]

}



locals  {
  part1 = [for v in var.input:
      {
        "val" = v.x,
        "description" = "This is a value of X"
      }]
      
  part2 = [for v in var.input:
      {
        "val" = v.y,
        "description" = "This is a value of Y"
      }]      
}



output "output" {

  value = concat(local.part1, local.part2)

}

The output from my tests:

utput = [
  {
    "description" = "This is a value of X"
    "val" = "X1"
  },
  {
    "description" = "This is a value of X"
    "val" = "X2"
  },
  {
    "description" = "This is a value of X"
    "val" = "X3"
  },
  {
    "description" = "This is a value of Y"
    "val" = "Y1"
  },
  {
    "description" = "This is a value of Y"
    "val" = "Y2"
  },
  {
    "description" = "This is a value of Y"
    "val" = "Y3"
  },
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM