Using VM System Assigned Managed Identity in Azure Active Directory
In this we will learn and understand about accessing the Azure Resource Manager API using a Windows virtual machine with system-assigned managed identity enabled. We will discuss about granting VM access to a Resource Group in Azure Resource Manager and getting an access token using the VM identity and use it to call Azure Resource Manager
Azure Managed Identity
Managing identity for Azure resources is a feature of Azure Active Directory. Each of the Azure services supportING managed identities for Azure resources are subject to their own timeline.
Granting VM access to a resource group in Resource Manager
With using managed identity for Azure resources, your code can get access tokens for authenticating to resources that support Azure AD authentication. However, the Azure Resource Manager supports Azure AD authentication. For this, we need to grant this VM’s system-assigned managed identity access to a resource in Resource Manager. For this case the Resource Group in which the VM is contained.
- Firstly, navigate to the tab for Resource Groups.
- Secondly, select the specific Resource Group you created for your Windows VM.
- Thirdly, go to Access control (IAM) in the left panel.
- Then, adding a role assignment that is a new role assignment for your Windows VM. Choose Role as Reader.
- After that, in the next drop-down, assign access to the resource Virtual Machine.
- Then, ensure the proper subscription is listed in the Subscription dropdown. And for Resource Group, select All resource groups.
- Lastly, Select choose your Windows VM in the dropdown and click Save.
Getting an access token using the VM’s system-assigned managed identity and using it to call Azure Resource Manager
For this portion you will require the use of PowerShell.
- Firstly, in the portal, navigate to Virtual Machines and go to your Windows virtual machine and in the Overview. Then, click Connect.
- Secondly, enter your Username and Password for which you added when you created the Windows VM.
- Now that you have created a Remote Desktop Connection with the virtual machine just open PowerShell in the remote session.
- Then, with the Invoke-WebRequest cmdlet, make a request to the local managed identity for Azure resources endpoint for getting an access token for Azure Resource Manager.
In PowerShell:
$response = Invoke-WebRequest -Uri ‘http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/’ -Method GET -Headers @{Metadata=”true”}
- After that, extract the full response, which is stored as a JavaScript Object Notation (JSON) formatted string in the $response object.
In PowerShell:
$content = $response.Content | ConvertFrom-Json
- Then, extract the access token from the response.
In PowerShell:
$ArmToken = $content.access_token
- Lastly, call Azure Resource Manager using the access token.
Reference: Microsoft Documentation