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 = [
"[email protected]",
"[email protected]",
]
}
tf-group-b = {
members = [
"[email protected]",
"[email protected]",
]
}
}
}
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:[email protected]" = {
"group" = "tf-group-a"
"member" = "[email protected]"
}
"tf-group-a:[email protected]" = {
"group" = "tf-group-a"
"member" = "[email protected]"
}
"tf-group-b:[email protected]" = {
"group" = "tf-group-b"
"member" = "[email protected]"
}
"tf-group-b:[email protected]" = {
"group" = "tf-group-b"
"member" = "[email protected]"
}
}