How to recursively create nested Azure Management Groups using Terraform?

589 views Asked by At

I am trying to create nested management groups recursively in Terraform and I can't seem to be able to achieve it using count or for or for_each. The best I have been able to achieve is to filter Tenant level and non-tenant level groups but that would still not help me create them recursively.

Any idea on how this can be achieved?

locals {
  managementGroups = [
    {
      id          = "MainGroupOne"
      displayName = "Main Group One"
      parent      = "Tenant Root Group"
    },
    {
      id          = "MainGroupTwo"
      displayName = "Main Group Two"
      parent      = "Tenant Root Group"
    },
    {
      id          = "GroupOne"
      displayName = "Group One"
      parent      = "MainGroupOne"
      subscriptions = [
        "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"
      ]
    },
    {
      id          = "ChildOne"
      displayName = "Child One"
      parent      = "GroupOne"
      subscriptions = [
        "ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ"
      ]
    },
    { id          = "GroupTwo"
      displayName = "Group Two"
      parent      = "MainGroupOne"
    },
    { id          = "GroupThree"
      displayName = "Group Three"
      parent      = "MainGroupTwo"
    }
  ]
}

locals {
  rootGroups = [
    for grp in local.managementGroups : grp
    if grp.parent == "Tenant Root Group"
  ]

  nonRootGroups = [
    for grp in local.managementGroups : grp
    if grp.parent != "Tenant Root Group"
  ]
}

output "rootGroups" {
  value = local.rootGroups
}

output "nonRootGroups" {
  value = local.nonRootGroups
}

resource "azurerm_management_group" "root_groups" {
  count = length(local.rootGroups)

  name             = local.rootGroups[count.index].id
  display_name     = local.rootGroups[count.index].displayName
}

resource "azurerm_management_group" "nonroot_groups" {
  count = length(local.nonRootGroups)

  name         = local.nonRootGroups[count.index].id
  display_name = local.nonRootGroups[count.index].displayName

  ############### PROBLEM AREA ###############
  # parent_management_group_id = ?
  ############### PROBLEM AREA ###############
}

Edit: I want to achieve something like this but without hardcoding anything in the config itself.

enter image description here

1

There are 1 answers

0
user20302417 On
data "azurerm_subscription" "current" {}

locals {
    tenant_root_group_id = "/providers/Microsoft.Management/managementGroups/${data.azurerm_subscription.current.tenant_id}"
}