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

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. 此示例展示了如何使用 Azure CLI 授予 Azure 虚拟机或虚拟机规模集的托管标识对 Azure 存储帐户的访问权限。This example shows you how to give an Azure virtual machine or virtual machine scale set's managed identity access to an Azure storage account using Azure CLI.

先决条件Prerequisites

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

在 Azure 资源(如 Azure 虚拟机Azure 虚拟机规模集)上启用托管标识后:After you've enabled managed identity on an Azure resource, such as an Azure virtual machine or Azure virtual machine scale set:

  1. 此示例要授予 Azure 虚拟机对存储帐户的访问权限。In this example, we are giving an Azure virtual machine access to a storage account. 首先,我们使用 az resource list 获取名为 myVM 的虚拟机的服务主体:First we use az resource list to get the service principal for the virtual machine named myVM:

    spID=$(az resource list -n myVM --query [*].identity.principalId --out tsv)
    

    对于 Azure 虚拟机规模集,使用的命令相同,但获取名为“DevTestVMSS”的虚拟机规模集的服务主体:For an Azure virtual machine scale set, the command is the same except here, you get the service principal for the virtual machine scale set named "DevTestVMSS":

    spID=$(az resource list -n DevTestVMSS --query [*].identity.principalId --out tsv)
    
  2. 获得服务主体 ID 后,立即使用 az role assignment create授予虚拟机或虚拟机规模集对“myStorageAcct”存储帐户的“读者”访问权限:Once you have the service principal ID, use az role assignment create to give the virtual machine or virtual machine scale set "Reader" access to a storage account called "myStorageAcct":

    az role assignment create --assignee $spID --role 'Reader' --scope /subscriptions/<mySubscriptionID>/resourceGroups/<myResourceGroup>/providers/Microsoft.Storage/storageAccounts/myStorageAcct
    

后续步骤Next steps