Dynamic reference to resource (provide full scope to assignment)

Hi everyone!
I have a problem with change name of the reference, but from the beginning.
I’m creating few levels of azurerm_management_group because I can’t refer in parent_management_group_id parameter to the same resource when applying, so code for this looks like below:

resource "azurerm_management_group" "mg-lvl_0" {
  for_each     = var.mg-struct.lvl_0
  display_name = each.value["name"]
  name         = each.value["name"]
}

resource "azurerm_management_group" "mg-lvl_1" {
  for_each                   = var.mg-struct.lvl_1
  display_name               = each.value["name"]
  name                       = each.value["name"]
  parent_management_group_id = azurerm_management_group.mg-lvl_0[each.value["PID"]].id
  depends_on                 = [azurerm_management_group.mg-lvl_0]
}

I have few more levels there, terraform state list return

azurerm_management_group.mg-lvl_0["m0000"]
azurerm_management_group.mg-lvl_1["m0001"]

Now i want to use azurerm_role_assignment and I need to use the same level separation for this operation because I can’t found any solution to dynamic change x in lvl_x.

resource "azurerm_role_assignment" "IAM-lvl_0" {
  for_each             = local.role-map-lvl_0
  scope                = azurerm_management_group.mg-lvl_0[each.value["scope"]].id
  role_definition_name = each.value["role"]
  principal_id         = each.value["PID"]
}

resource "azurerm_role_assignment" "IAM-lvl_1" {
  for_each             = local.role-map-lvl_1
  scope                = azurerm_management_group.mg-lvl_1[each.value["scope"]].id
  role_definition_name = each.value["role"]
  principal_id         = each.value["PID"]
}

All what I want to do is marge this two section into single one, for this I need to change lvl_0 to another number in scope parameter
Is it possible in terraform?

Edit:
I try to provide variable in $$ but terraform treats it like single segment:
expected 4 segments within the Resource ID but got 1
code in locals:

"scope" = "$${azurerm_management_group.mg-lvl_0[\"m0000\"].id}"

of course i changed scope in IAM section to

scope = each.value["scope"]

Hi @rebel123,

If there are no colliding keys between local.role-map-lvl_0 and local.role-map-lvl_1 then you can merge the maps representing the instances of those two resources together into a single map:

locals {
  role_assignments = merge(
    azurerm_role_assignment.IAM-lvl_0,
    azurerm_role_assignment.IAM-lvl_1,
  )
}

You can then use expressions like local.role_assignments["m0000"] to access individual role assignment objects without worrying about which of the two resources each one came from.

Hello @apparentlymart

Awesome! That was exactly what i needed!
I merged management groups and now I can refer to everyone using single local variable, thanks a lot!