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 = [
        "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
  }
}

View the resulting map

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

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