如何使自定义角色的范围成为天蓝色的资源组?

How do I make the scope of a custom role be Resourcegroup in azure?

我已经编写了用于创建用户、资源组和角色定义的地形。

我需要让资源定义的范围成为我创建的资源组。

我不知道该怎么做。如果有人可以提供帮助,那就太好了。

########### for creating user ####

# Configure the Azure Provider
provider "azurerm" {
  version = "~> 1.30"
  subscription_id="723604be-b74b-4473-9d11-1802dbfdb787"
}

provider "azuread" {
  version = "~> 0.4"
  subscription_id="723604be-b74b-4473-9d11-1802dbfdb787"
}

resource "azuread_user" "test" {
  user_principal_name = "user1@catch.whizlabstesting.com"
  display_name        = "User1"
  mail_nickname       = "User1"
  password            = "Muneeshpandi@17"
  force_password_change = "false"
}

##### creating resource group #####

resource "azurerm_resource_group" "terraform_rg" {
  name = "user1_rgp"
  location = "East US"
    }

########## creating role definition ##########

data "azurerm_subscription" "primary" {}

resource "azurerm_role_definition" "sql_role" {
  name        = "sql_role"
  scope       = "data.azurerm_subscription.primary.id"
  description = "This is a custom role to create sql database"

  permissions {
    actions     = ["*"]
    not_actions = []
  }

  assignable_scopes =  [
   "/subscriptions/723604be-b74b-4473-9d11-1802dbfdb787/resourceGroups/user1_rgp"
  ]
}

执行上述代码时出现以下错误:

Error: authorization.RoleDefinitionsClient#CreateOrUpdate: Failure responding to request: StatusCode=404 -- Original Error: autorest/azure: Service returned an error. Status=404 Code="MissingSubscription" Message="The request did not have a subscription or a valid tenant level resource provider."

如何在 Azure 中将自定义角色的范围设置为资源组?

要为资源组创建自定义角色,您需要有权限Microsoft.Authorization/roleDefinitions/write,要为用户分配自定义角色,您需要有权限Microsoft.Authorization/roleAssignments/write。最简单的方法是您拥有订阅的 Onwer 角色。

并创建一个 Azure AD 用户:

To add or delete users you must be a User administrator or Global administrator.

当您拥有所有需要的权限时。让我们专注于您的代码。您还需要将自定义角色分配给您在资源组范围内创建的用户。然后你可以像这样更改代码:

resource "azurerm_role_definition" "sql_role" {
  name        = "sql_role"
  scope       = data.azurerm_subscription.primary.id
  description = "This is a custom role to create sql database"

  permissions {
    actions     = ["*"]
    not_actions = []
  }

  assignable_scopes =  [
   data.azurerm_subscription.primary.id
  ]
}

resource "azurerm_role_assignment" "example" {
  scope              = azurerm_resource_group.terraform_rg.id
  role_definition_id = azurerm_role_definition.sql_role.id
  principal_id       = azuread_user.test.id
}

如果您只希望自定义可用于资源组,您可以将assignable_scopes 与资源组ID 更改为azurerm_resource_group.terraform_rg.id