使用 PowerShell 向托管标识分配对资源的访问权限Assign a managed identity access to a resource using PowerShell

Azure 资源的托管标识是 Azure Active Directory 的一项功能。Managed identities for Azure resources is a feature of Azure Active Directory. 支持 Azure 资源的托管标识的每个 Azure 服务都受其自己的时间线限制。Each of the Azure services that support managed identities for Azure resources are subject to their own timeline. 在开始之前,请务必查看资源的托管标识的可用性状态以及已知问题Make sure you review the availability status of managed identities for your resource and known issues before you begin.

为 Azure 资源配置托管标识后,便可以授予该托管标识对其他资源的访问权限,这一点与安全主体一样。Once you've configured an Azure resource with a managed identity, you can give the managed identity access to another resource, just like any security principal. 本示例展示了如何使用 PowerShell 为 Azure 虚拟机的托管标识提供对 Azure 存储帐户的访问权限。This example shows you how to give an Azure virtual machine's managed identity access to an Azure storage account using PowerShell.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

先决条件Prerequisites

使用 Azure RBAC 授予托管标识对另一资源的访问权限Use Azure RBAC to assign a managed identity access to another resource

  1. 在 Azure 资源上启用托管标识,如 Azure VMEnable managed identity on an Azure resource, such as an Azure VM.

  2. 此示例要授予 Azure VM 对存储帐户的访问权限。In this example, we are giving an Azure VM access to a storage account. 首先,我们使用 Get-AzVM 获取名为 myVM 的 VM 的服务主体,该 VM 是在启用托管标识时创建的。First we use Get-AzVM to get the service principal for the VM named myVM, which was created when we enabled managed identity. 然后,使用 New-AzRoleAssignment 向 VM 提供对名为 myStorageAcct 的存储帐户的“读者”访问权限:Then, use New-AzRoleAssignment to give the VM Reader access to a storage account called myStorageAcct:

    $spID = (Get-AzVM -ResourceGroupName myRG -Name myVM).identity.principalid
    New-AzRoleAssignment -ObjectId $spID -RoleDefinitionName "Reader" -Scope "/subscriptions/<mySubscriptionID>/resourceGroups/<myResourceGroup>/providers/Microsoft.Storage/storageAccounts/<myStorageAcct>"
    

后续步骤Next steps