首页 > 解决方案 > 使用 terraform 将角色分配添加到托管标识的多个 Azure 订阅

问题描述

我有一个托管在订阅“sub-test1”中的 Azure 函数应用程序,我想添加角色分配以授予托管系统标识(应用程序)访问订阅“sub-test1”(当前)的权限,并且我已经能够通过以下方式做到这一点:

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
}

但我需要让这个应用程序访问租户内的多个订阅(动态编号),比如“sub-test2”、“sub-test3”、“sub-test4”等。仅使用 terraform 的最佳方法是什么?此外,这是否可以仅使用一个“azurerm_role_assignment”资源块来完成,如上所示,还是每个订阅都需要多个这样的块?

标签: azureazure-functionsterraformterraform-provider-azure

解决方案


对于此要求,您需要有足够的权限才能在订阅中为其创建角色分配。最简单的方法是您需要拥有所有订阅的所有者角色。然后你可以改变这样的代码来实现你想要的:

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
}

这是不同的东西。使用azurerm_subscriptions而不是azurerm_subscription获取所有订阅。但它只获取订阅的 GUID。所以我们需要自己填写订阅的资源Id。也用于角色定义。


推荐阅读