Assign a managed identity access to a resource using Azure CLI

Managed identities for Azure resources is a feature of Azure Active Directory. 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 the Bash environment in Azure Cloud Shell.

    Launch Cloud Shell in a new window

  • If you prefer, install the Azure CLI to run CLI reference commands.

    • If you're using a local installation, sign in to the Azure CLI by using the az login command. To finish the authentication process, follow the steps displayed in your terminal. For additional sign-in options, see Sign in with the Azure CLI.

    • When you're prompted, install Azure CLI extensions on first use. For more information about extensions, see Use extensions with the Azure CLI.

    • Run az version to find the version and dependent libraries that are installed. To upgrade to the latest version, run az upgrade.

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