for_each in Terraform does not support nested for_each's, but nested configurations can be flattened using nested for loops in a locals section.
This example is needed with a resource that binds users to groups, with a one to one mapping between the group and the member.
resource "databricks_group_member" "ab" {
group_id = databricks_group.a.id
member_id = databricks_group.b.id
}
Adapted from Terraform's flatten example.
variable "groups" {
type = map(object({
members = list(string)
}))
default = {
tf-group-a = {
members = [
"fred.bloggs@example.com",
"john.doe@example.com",
]
}
tf-group-b = {
members = [
"danny.boy@example.com",
"someone.else@example.com",
]
}
}
}
locals {
# flatten ensures that this local value is a flat list of objects, rather
# than a list of lists of objects.
tf_groups = flatten([
for group_name, group in var.groups : [
for member in group.members : {
group = group_name
member = member
}
]
])
tf_groups_map = {
for g in local.tf_groups: "${g.group}:${g.member}" => g
}
}
# terraform console
> local.tf_groups_map
{
"tf-group-a:fred.bloggs@example.com" = {
"group" = "tf-group-a"
"member" = "fred.bloggs@example.com"
}
"tf-group-a:john.doe@example.com" = {
"group" = "tf-group-a"
"member" = "john.doe@example.com"
}
"tf-group-b:danny.boy@example.com" = {
"group" = "tf-group-b"
"member" = "danny.boy@example.com"
}
"tf-group-b:someone.else@example.com" = {
"group" = "tf-group-b"
"member" = "someone.else@example.com"
}
}