Search code examples
listterraformtransformhcl

Terraform - transform list of lists to into a new list of lists


In Terraform, I need to transform my input data structure from e.g.:

vip_lists = [
    ["1.0.1.1", "1.0.1.2", "1.0.1.3", "1.0.1.4"]
    ["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"]
    ["1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"]
]

to produce an output like this:

vip_sets = [
    ["1.0.1.1", "1.0.2.1", "1.0.0.1"]
    ["1.0.1.2", "1.0.2.2", "1.0.0.2"]
    ["1.0.1.3", "1.0.2.3", "1.0.0.3"]
    ["1.0.1.4", "1.0.2.4", "1.0.0.4"]
]

So essentially, i need to take my input list of lists and create an output which is again a list of lists but whose 0th list is a list of the 0th elements from each of the lists in the input...then the same again for the 1st and so on. I can't know in advance how many lists will be in the input or how long they will be, but we can assume the lists will all be the same length if that helps.

I've tried pretty much everything I can think of and searched the web but since with no luck. All suggestions would be very welcome!


Solution

  • This is sort of horrible, but it works (Although I haven't tested what it'd do if vip_lists was empty. Probably crash, as I'm indexing to vip_lists[0] without checking):

    locals {
      vip_lists = [
        ["1.0.1.1", "1.0.1.2", "1.0.1.3", "1.0.1.4"],
        ["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"],
        ["1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"]
      ]
    
      vip_sets = [for i in range(0, length(local.vip_lists[0])): [for j in range(0, length(local.vip_lists)): local.vip_lists[j][i]]]
    }
    
    output "vip_sets" {
      value = local.vip_sets
    }
    
    $ terraform apply
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
    
    Outputs:
    
    vip_sets = [
      [
        "1.0.1.1",
        "1.0.2.1",
        "1.0.0.1",
      ],
      [
        "1.0.1.2",
        "1.0.2.2",
        "1.0.0.2",
      ],
      [
        "1.0.1.3",
        "1.0.2.3",
        "1.0.0.3",
      ],
      [
        "1.0.1.4",
        "1.0.2.4",
        "1.0.0.4",
      ],
    ]