Assign a managed identity access to a resource using Azure CLI

Managed identities for Azure resources is a feature of Microsoft Entra ID. 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.

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. 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.

If you don't already have an Azure account, sign up for a free account before continuing.

Prerequisites

Use Azure RBAC to assign a managed identity access to another resource

After you've enabled managed identity on an Azure resource, such as an Azure virtual machine or Azure virtual machine scale set:

  1. In this example, we are giving an Azure virtual machine access to a storage account. 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)
    

    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. 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