简体   繁体   中英

Adding role assignments to multiple Azure subscriptions for a managed identity using terraform

I have an Azure function app that is hosted in subscription "sub-test1" and I want to add role assignment to give the managed system identity(for app) access to the subscription "sub-test1"(current) and I have been able to do it via the following:

data "azurerm_subscription" "current" {}

data "azurerm_role_definition" "owner" {
  name = "Owner"
}

resource "azurerm_role_assignment" "custom_role_assignment" {
  name               = "${var.random_guid}"
  scope              = data.azurerm_subscription.current.id
  role_definition_id = "${data.azurerm_subscription.current.id}${data.azurerm_role_definition.owner.id}"
  principal_id       = azurerm_function_app.app.identity.0.principal_id
}

But I need to give this app access to multiple subscriptions(dynamic number) inside the tenant, say "sub-test2","sub-test3","sub-test4",etc. What is the best way I can do it using terraform only? Also, can this be done using only one "azurerm_role_assignment" resource block as shown above or do I need multiple such blocks respective to each subscription?

For this requirement, you need to have enough permission to create the role assignment for in the subscriptions. The simplest way is that you need to have the Owner role of all the subscriptions. Then you can change the code like this to achieve what you want:

data "azurerm_subscriptions" "example" {}

data "azurerm_role_definition" "example" {
    name = "Owner"
}

resource "azurerm_role_assignment" "custom_role_assignment" {
  count              = length(data.azurerm_subscriptions.example.subscriptions.*.subscription_id)
  name               = "${var.random_guid}"
  scope              = "/subscriptions/${element(data.azurerm_subscriptions.example.subscriptions.*.subscription_id, count.index)}"
  role_definition_id = "/subscriptions/${element(data.azurerm_subscriptions.example.subscriptions.*.subscription_id, count.index)}${data.azurerm_role_definition.example.id}"
  principal_id       = azurerm_function_app.app.identity.0.principal_id
}

Here is something different. Use the azurerm_subscriptions instead of azurerm_subscription to get all the subscriptions. But it only gets the GUID of the subscriptions. So we need to complete the resource Id of the subscriptions ourselves. Also for the role definition.

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