Use PowerShell to grant a managed identity access to a resource

This article shows you how to use PowerShell to give a managed identity access to an Azure resource. In this article, we use the example of an Azure virtual machine (Azure VM) managed identity accessing an Azure storage account. Once you've configured an Azure resource with a managed identity, you can then give the managed identity access to another resource, similar to any security principal.

Prerequisites

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

Note

We recommend that you use the Azure Az PowerShell module to interact with Azure. See Install Azure PowerShell to get started. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

Run scripts locally by installing the latest version of Azure PowerShell, then sign in to Azure using Connect-AzAccount -Environment AzureChinaCloud.

  1. Enable managed identity on an Azure resource, such as an Azure VM.

  2. Give the Azure virtual machine (VM) access to a storage account.

    1. Use Get-AzVM to get the service principal for the VM named myVM, which was created when you enabled managed identity.
    2. 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