Azure AD - Create Group and do User to Group assignement

Hi there,
I have create following terraform code to do following things on Azure:

  • Create AAD Groups for each role for a Management Group
  • Assigne that Group with right role to Management Group
  • add users to aad groups

My config looks like

locals {
  user_group_assignement =  {
    "sam@example.com" = ["some_group_name"]
    "tom@example.com" = ["some_group_name"]
  }
  aad_groups_to_mg = [
    {
      group_prefix = "some_group_name"
      management_group = "Some Management Group Name"
      roles = ["Reader", "Contributor", "Owner"]
    }
  ]
 
  aad_groups_to_role_to_mg_map = distinct(flatten([
    for grp in local.aad_groups_to_mg : [
      for rol in grp.roles : {
        group_name = lower("${grp.group_prefix}-${rol}")
        role = rol
        management_group = grp.management_group
      }
    ]
  ]))

}

module "user_to_groups" {
  for_each = local.user_group_assignement
  source = "./modules/user_to_groups"
  user = each.key
  groups = each.value
}

module "aad_groups_to_mg" {
  source            = "./modules/aad_groups_to_mg"
  for_each          =  { for entry in local.aad_groups_to_role_to_mg_map: "${entry.group_name}" => entry }
  group_name        = each.value.group_name
  management_group  = each.value.management_group
  role              = each.value.role
}

The error we receive is

│ Error: No group found with display name: “some_group_name”

│ with module.user_to_groups[“sam@example.com”].data.azuread_groups.all_groups,
│ on modules\user_to_groups\main.tf line 6, in data “azuread_groups” “all_groups”:
│ 6: display_names = var.groups

Which makes “sense” as the group will be created by module.aad_groups_to_mg

The workaround I see is

#create groups and assignements of groups to mg first
terraform plan -target module.aad_groups_to_mg
# do any other change
terraform plan

We don’t wan’t to maintain the group membership withhin locals.aad_groups_to_mg as we want to see the “groups of a user” in the code easily.

Any suggestion on this “what was first, chicken or egg” issue?
Many thanks
Joerg