azure-virtual-machineazure-rest-apiazure-identity

Enable both system-assigned and user assigned identities to Azure Virtual Machine simultaneously in single REST API call


I'm attempting to configure an Azure Virtual Machine (VM) to have both a system assigned managed identity (MSI) and a user assigned managed identity using REST API calls. While I've been able to enable one or the other using PowerShell, I'm struggling to find documentation or examples on how to enable both simultaneously via REST API.

Here's the PowerShell code I've tried so far:

  1. Enabling system assigned managed identity:

    $vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName Update-AzVM -ResourceGroupName $resourceGroupName -VM $vm -IdentityType SystemAssigned

  2. Assigning user assigned managed identity:

    $vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName Update-AzVM -ResourceGroupName $resourceGroupName -VM $vm -IdentityType UserAssigned -IdentityID "/subscriptions/<SUBSCRIPTION ID>/resourcegroups/<RESOURCE GROUP>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<USER ASSIGNED IDENTITY NAME>"

While these PowerShell commands work individually, I'm having trouble combining them to enable both types of managed identities for the Azure VM.

Could someone provide guidance or examples on how to achieve this using REST API calls? Specifically, I'm looking for the equivalent REST API requests to achieve the configurations mentioned above.

I already have a service principal with clientId, secret, and tenant to create a OAuth2 token, and it has the necessary contributor role under the subscription.


Solution

  • Initially, I generated one bearer token for service principal having "Contributor" role under subscription via Postman like this:

    POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
    grant_type:client_credentials
    client_id:appID
    client_secret:secret
    scope: https://management.azure.com/.default
    

    Response:

    enter image description here

    To enable both system-assigned and user assigned identities to Azure Virtual Machine simultaneously, make use of below API call:

    PATCH https://management.azure.com/subscriptions/<SUBSCRIPTION ID>/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2017-12-01 HTTP/1.1
    {
        "identity":{
           "type":"SystemAssigned,UserAssigned",
           "identityIds":[
              "/subscriptions/<SUBSCRIPTION ID>/resourcegroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ID1"
           ]
        }
     }
    

    Response:

    enter image description here

    When I checked the same in Portal, both identities enabled successfully in virtual machine as below:

    enter image description here

    enter image description here

    Reference: Configure managed identities on Azure VM using REST | Microsoft