访问/引用由 for_each 创建的资源

时间:2021-02-24 01:12:07

标签: azure terraform terraform-provider-azure

我目前正在尝试为我的所有订阅创建多个 azurerm_role_definition 及其对应的 azurerm_role_assignment。我想动态地执行此操作,而不是使用 subscription_id 值进行硬编码。我能够创建 subscriptions_map 的地图,然后使用 for_each 创建 azurerm_role_defitions(s)。但是,现在我需要引用 azurerm_role_assignment 中的定义。最好的方法是什么?


# Configure the Microsoft Azure Provider
provider "azurerm" {
  features {}
}

# AD App
resource "azuread_application" "test-app" {
  display_name = "test-app"
}

# Service Principal
resource "azuread_service_principal" "test-app" {
  application_id = azuread_application.test-app.application_id
}

# Available subscriptions
data "azurerm_subscriptions" "available" {
}

locals {
  subscriptions_map = {
    for obj in data.azurerm_subscriptions.available.subscriptions.* : obj.display_name => obj
  }
}

# Role definition 
resource "azurerm_role_definition" "test-app" {
  for_each           = local.subscriptions_map
  role_definition_id = "00000000-0000-0000-0000-000000000000"
  name               = "custom-role-definition-${each.value.display_name}"
  scope              = each.value.id
  
  permissions {
    actions     = ["Microsoft.Resources/subscriptions/resourceGroups/read"]
    not_actions = []
  }

  assignable_scopes = [
    each.value.id,
  ]
}

# Role assignment 
resource "azurerm_role_assignment" "test-app" {
  for_each           = local.subscriptions_map
  name               = "00000000-0000-0000-0000-000000000000"
  scope              = each.value.id

  #Help here
  role_definition_id = azurerm_role_definition.test-app.*.role_definition_resource_id
  
  principal_id       = azuread_service_principal.test-app.object_id
}

1 个答案:

答案 0 :(得分:1)

由于您在 for_each 中使用了 azurerm_role_definition.test-app,因此您可以参考由键名创建的各个定义。所以你的 azurerm_role_assignment.test-app 可能是:

# Role assignment 
resource "azurerm_role_assignment" "test-app" {

  for_each           = local.subscriptions_map

  name               = "00000000-0000-0000-0000-000000000000"
  scope              = each.value.id

  #Help here
  role_definition_id = azurerm_role_definition.test-app[each.key].role_definition_resource_id
  
  principal_id       = azuread_service_principal.test-app.object_id
}