For_each over a set of objects, creating keys from an object property that is a list of strings

I have a variable that is a list of objects, similar to

variable "rules" {
  type = list(object({
    names = list(string)
    foo = string
  }))
}

I’m using this variable to create multiple resources like so:

resource "foo_resource" "this" {
    for_each = { ... }

    ...
}

What I’d like to do is to be able to transform the following list of objects:

locals {
  input = [
    {
      names = ["a", "b"]
      foo = "something"
    },
    {
      names = ["c", "d"]
      foo = "something-else"
  ]
}

into the following map:

locals {
  desired_output = {
    "a" => { foo => "something" }
    "b" => { foo => "something" }
    "c" => { foo => "something-else" }
    "d" => { foo => "something-else" }
  }
}

thoughts on how to accomplish this?

Iterating over two nested levels and then compiling a map from the results is a very common pattern in Terraform - it’s a bit complex how it needs to be written, though.

I’m on mobile right now so can’t type complex code, but here’s the last time I answered approximately this question: Attach multiple policy to single SSO permission set - #2 by maxb

You should be able to adapt the code I have there to do what you want, by swapping out some of the subexpressions.

Any problems, comment here and I’ll be more explicit when I have a real keyboard to work with.

ah, i was missing the outer loop.

this worked perfectly, thanks for breaking my tunnel vision:

resource "foo_resource" "this" {
  for_each = {
    for rule in flatten([
      for r in var.rules : [
        for n in r.names : {
          name = n
          foo = r.foo
        }
      ]
    ]) : rule.name => rule
  }
}