使用terraform将角色分配添加到多个Azure订阅中以获得托管身份

时间:2020-07-27 19:38:41

标签: azure azure-functions terraform terraform-provider-azure

我有一个Azure函数应用程序,该应用程序托管在订阅“ sub-test1”中,并且我想添加角色分配,以使受管系统身份(用于应用程序)访问订阅“ 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”资源块(如上所示)来完成此操作,还是我需要针对每个订阅分别使用多个这样的块?

1 个答案:

答案 0 :(得分:0)

为此要求,您需要具有足够的权限才能在订阅中创建角色分配。最简单的方法是,您需要具有所有订阅的所有者角色。然后,您可以像这样更改代码以实现所需的内容:

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。也用于角色定义。

相关问题