Wondering how I would go about doing the following:
provider "azurerm" {
features {}
}
variable "management_groups" {
type = list(object({
display_name = string
unique_name = string
parent = optional(string, "")
}))
default = [{
display_name = "Platform"
unique_name = "mg-platform"
parent = "mg-org"
}, {
display_name = "Connectivity"
unique_name = "mg-connectivity"
parent = "mg-platform"
}, {
display_name = "Identity"
unique_name = "mg-identity"
parent = "mg-platform"
}]
}
locals {
_core_management_group_map = {
for management_group in var.management_groups : management_group.unique_name => management_group
}
_core_management_group_data = {
# See: https://github.com/hashicorp/terraform/issues/22281#issuecomment-517080564
for v in compact(setsubtract(distinct(values(local._core_management_group_map)[*].parent), distinct(values(local._core_management_group_map)[*].unique_name))) : v => v
}
}
data "azurerm_management_group" "core_management_group" {
# for every parent without a matching unique_name.
for_each = local._core_management_group_data
name = each.key
}
resource "azurerm_management_group" "core_management_group" {
for_each = {
for management_group in var.management_groups : management_group.unique_name => management_group
}
parent_management_group_id = each.value.parent != "" ? try(data.azurerm_management_group.core_management_group[each.key].id, azurerm_management_group.core_management_group[each.value.parent].id) : null
display_name = each.value.display_name
name = each.value.unique_name
}