简体   繁体   中英

Accessing/referencing resources created by for_each

I am currently trying to create multiple azurerm_role_definition with their corresponding azurerm_role_assignment for all my subscriptions. I want to do this dynamically and not hard code with subscription_id values. I am able to create create a map of subscriptions_map and then with a for_each create the azurerm_role_defitions (s). However, now I need to reference the definitions in the azurerm_role_assignment . What would be the best approach for this?


# 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
}

Since you've used for_each in azurerm_role_definition.test-app , you can refer to the individual definitions created by key name. So your azurerm_role_assignment.test-app could be:

# 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM