Skip to content

Instantly share code, notes, and snippets.

@john-auld
Last active July 5, 2022 09:34
Show Gist options
  • Save john-auld/2f0c813abfd6240ea48a62fd6314cbb0 to your computer and use it in GitHub Desktop.
Save john-auld/2f0c813abfd6240ea48a62fd6314cbb0 to your computer and use it in GitHub Desktop.
Terraform flatten to manipulate structured configuration

Flatten a list of lists of objects

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
}

The solution

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
  }
}

View the resulting map

# 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]"
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment