快速入門:使用 Bicep 指派 Azure 角色

Azure 角色型存取控制 (Azure RBAC) 是您可用來管理 Azure 資源存取權的方法。 在本快速入門中,您會建立資源群組,並授與使用者建立和管理資源群組中虛擬機器的存取權。 本快速入門會使用 Bicep 來授與存取權。

Bicep 是使用宣告式語法來部署 Azure 資源的特定領域語言 (DSL)。 其提供簡潔的語法、可靠的類型安全,並支援程式碼重複使用。 Bicep 為 Azure 中的基礎結構即程式碼解決方案提供最佳撰寫體驗。

必要條件

若要指派 Azure 角色並移除角色指派,您必須具備:

  • 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶
  • Microsoft.Authorization/roleAssignments/writeMicrosoft.Authorization/roleAssignments/delete 許可權,例如 角色型存取控制 管理員istrator
  • 若要指派角色,您必須指定三個元素:安全性主體、角色定義和範圍。 在本快速入門中,安全性主體是您或目錄中的另一位使用者,角色定義是 虛擬機器參與者 ,而範圍是您指定的資源群組。

檢閱 Bicep 檔案

此快速入門中使用的 Bicep 檔案是來自 Azure 快速入門範本。 Bicep 檔案有兩個參數和資源區段。 在 [資源] 區段中,請注意其具有角色指派的三個元素:安全性主體、角色定義和範圍。

@description('Specifies the role definition ID used in the role assignment.')
param roleDefinitionID string

@description('Specifies the principal ID assigned to the role.')
param principalId string

var roleAssignmentName= guid(principalId, roleDefinitionID, resourceGroup().id)
resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: roleAssignmentName
  properties: {
    roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionID)
    principalId: principalId
  }
}

output name string = roleAssignment.name
output resourceGroupName string = resourceGroup().name
output resourceId string = roleAssignment.id

Bicep 檔案中定義的資源為:

部署 Bicep 檔案

  1. 將 Bicep 檔案儲存為 main.bicep 到本機電腦。

  2. 使用 Azure CLI 或 Azure PowerShell 部署 Bicep 檔案。

    az group create --name exampleRG --location eastus
    az deployment group create --resource-group exampleRG --template-file main.bicep --parameters roleDefinitionID=9980e02c-c2be-4d73-94e8-173b1dc7cf3c principalId=<principal-id>
    

注意

將 principal-id > 取代 < 為指派給角色的主體識別碼。

當部署完成時,您應該會看到訊息,指出部署成功。

檢閱已部署的資源

使用 Azure 入口網站、Azure CLI 或 Azure PowerShell 來列出資源群組中已部署的資源。

az role assignment list --resource-group exampleRG

清除資源

不再需要時,請使用 Azure 入口網站、Azure CLI 或 Azure PowerShell 來移除角色指派。 如需相關資訊,請參閱移除 Azure 角色指派

使用 Azure 入口網站、Azure CLI 或 Azure PowerShell 刪除資源群組。

az group delete --name exampleRG

下一步