azurerm 角色分配,在提供者中使用 client_id、client_secret、subscription_id、tenant_id 时无法分配角色

azurerm role assignment, not able to assign role when used client_id, client_secret, subscription_id, tenant_id in provider

我正在使用 terraform 将“网络贡献者”角色分配给 azure vnet 并面临以下问题。 无法理解问题并请求您的帮助。

工作场景(成功将角色分配给 vnet):

  1. az 登录(它提供了设备代码并通过浏览器进行了身份验证)。
  2. 地形代码;
    terraform {
      required_providers {
        azurerm = {
           source  = "hashicorp/azurerm"
           version = "~> 2.0"
        }
    }
    required_version = "~> 1.0"
    }
    
    provider "azurerm" {
       features {}
    }
    
    resource "azurerm_role_assignment" "example" {
      scope              = "/subscriptions/xxx/resourceGroups/scale-rg/providers/Microsoft.Network/virtualNetworks/scale-vnet"
      role_definition_id = "/subscriptions/xxx/providers/Microsoft.Authorization/roleDefinitions/4d97b98b-1d4f-4787-a291-c67834d212e7"
      principal_id       = "393b9aba-8a3d-48f5-b5fe-c0ed0eb81ce5"
    }```
    
    

非工作场景(需要帮助):

  1. 不同的机器(没有 az 登录)
  2. 地形代码;
 terraform {
   required_providers {
     azurerm = {
       source  = "hashicorp/azurerm"
       version = "~> 2.0"
     }
   }
   required_version = "~> 1.0"
 }

provider "azurerm" {
  features {}

  use_cli         = false
  subscription_id = "xxx"
  client_id       = "xyz"
  client_secret   = "abc"
  tenant_id       = "fcf"
}

resource "azurerm_role_assignment" "example" {
   scope              = "/subscriptions/5cd3cd6f-667b-4a89-a046-de077806c368/resourceGroups/spectrum-scale-rg/providers/Microsoft.Network/virtualNetworks/spectrum-scale-vnet"
   role_definition_id = "/subscriptions/5cd3cd6f-667b-4a89-a046-de077806c368/providers/Microsoft.Authorization/roleDefinitions/4d97b98b-1d4f-4787-a291-c67834d212e7"
   principal_id       = "393b9aba-8a3d-48f5-b5fe-c0ed0eb81ce5"
 }

使用上面的client_id、tenant_id、subscription_id、client_secret(它们是从az account show获得的,并且能够成功创建其他资源像 vnet、子网等),它给出以下错误;

Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client '4d8a138b-5734-441a-a3cd-00f60be1d7c0' with object id '4d8a138b-5734-441a-a3cd-00f60be1d7c0' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/xxx/resourceGroups/scale-rg/providers/Microsoft.Network/virtualNetworks/scale-vnet/providers/Microsoft.Authorization/roleAssignments/144a2f0d-1f3b-fb7a-3e20-62261e44a9c1' or the scope is invalid. If access was recently granted, please refresh your credentials."

您收到此错误的原因是您 运行 使用的服务主体您的 Terraform 代码没有分配角色的权限。

要解决此问题,请在 Azure 订阅中为您的服务主体分配适当的 Azure RBAC 角色。允许角色分配的 RBAC 角色是 Owner or User Access Administrator.