簡體   English   中英

訪問/引用由 for_each 創建的資源

[英]Accessing/referencing resources created by for_each

我目前正在嘗試為我的所有訂閱創建多個azurerm_role_definition及其對應的azurerm_role_assignment 我想動態地執行此操作,而不是使用subscription_id值進行硬編碼。 我能夠創建一個 map 的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
}

由於您在azurerm_role_definition.test-app中使用了for_each ,因此您可以參考由鍵名創建的各個定義。 所以你的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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM