1
votes

I have an array of objects, and wanted to iterate only over specific objects (above this section in the resource there is count used fyi)

variable "x" {
  default = [
    first = [
      {
        a = 1
      },
      {
        b = 2
      }
    ]
    second = [
      {
        c = 3
      },
      {
        d = 4
      }
    ]
  ]
}

I have that array above as input, and wanted in the resource to loop only over elements from 'second' section, is there some way to do so ?

for_each = lookup(myvar, second) ?

or as I'm using, count and looping over the names ['first', 'second'] anyway in other section,

count         = length(var.names)
name          = "${element(var.names, count.index)}"

maybe I can reference that to get the right elemenets from the array ?

for_each = lookup(x[lookup(element(var.names, count.index))])
1

1 Answers

2
votes

If you fix the syntax for your x:


variable "x" {
  default = [ 
    {
    first = [
      {
        a = 1
      },
      {
        b = 2
      }
    ]},
    {
     second = [
      {
        c = 3
      },
      {
        d = 4
      }
    ]
  }
  ]
}

then you can locate the second as follows:

locals {
  key_to_find = "second"
  index_of_the_key = index(flatten([for v in var.x : keys(v)]), local.key_to_find)
}

Having the index you can iterate over the second values:

flatten([for elem in var.x[local.index_of_the_key]: elem])

# or 

flatten(values(var.x[local.index_of_the_key]))

which will produce the following list:

[
  {
    "c" = 3
  },
  {
    "d" = 4
  },
]