Foreach loop with nested list

Hello,

This is a bit of an abstract question rather than specific, but trying to figure out how the best way to achieve this type of scenario would be.

If i had a input which looked something like this

shares_and_folders = [
  {
    share_name = "share1"
    folders = ["folder1","folder2","folder3"
 },
{
    share_name = "share2"
    folders = ["folder1","folder2","folder3"
 }
]

how could i use that in a resource which needs both the share name and the folder names…

example

resource "folders" {
  share = var.share_and_folders.share_name
  folders = var.share_and_folders.folder_name 
}
type or paste code here

i would need to create a loop for both the share and the folders. 

I had a play with flatten but couldn't seem to figure it out, i thought of using setproduct but i don't think that would work as it would create each folder in every share for every share. 

i worked around it by changing the data structure, but was interested in seeing how i would accomplish such a scenario,.

You are on the right path by looking at flatten, but putting all the pieces together can be seriously non-intuitive… here is a working example using null_resource:

locals {
  shares_and_folders = [
    {
      share_name = "share1"
      folders    = ["folder1", "folder2", "folder3"]
    },
    {
      share_name = "share2"
      folders    = ["folder1", "folder2", "folder3"]
    },
  ]
}

resource "null_resource" "this" {
  for_each = {
    for combination in flatten([
      for share in local.shares_and_folders : [
        for folder in share.folders : {
          key    = "${share.share_name} ${folder}"
          share  = share
          folder = folder
        }
      ]
    ]) :
    combination.key => combination
  }

  triggers = {
    share  = each.value.share.share_name
    folder = each.value.folder
  }
}

ahhh - - that makes sense - so we use nested for loops to do it - that’s where I was getting stuck.

thank you