Overview and What You Will Learn
A managed identity is an identity in Microsoft Entra ID that Azure creates for a resource, such as a VM, and whose credentials Azure rotates for you, so your application never stores a password, client secret or certificate. It is a special kind of service principal with the credential management taken away. In this lab, you will create a System-Assigned identity and a User-Assigned identity, share the second across two VMs, grant it access with Azure RBAC, prove the access works, and watch how each identity type behaves when a VM is deleted.
- Telling System-Assigned and User-Assigned identities apart
- Comparing managed identities with service principals
- Attaching one User-Assigned identity to several VMs
- Granting access with a role assignment
- Requesting a token from the Instance Metadata Service
- Understanding identity lifecycle and orphaned role assignments
Why This Matters in Production
A developer at a fintech company like Stripe creates a service principal with a client secret so an application can call Azure services. The secret must be stored somewhere, rotated before it expires, and kept out of logs and config files, and an expired secret causes an outage at the worst moment. A managed identity removes that whole category of work, because there is no secret to store, rotate or leak.
Core Principles
Both identity types use the same security model: the VM asks the local metadata service for a token, and Entra ID issues one for that identity. They differ only in lifecycle and reuse. A System-Assigned identity is created with a resource and deleted with it. A User-Assigned identity is its own Azure resource, which you can attach to many resources and which survives any one of them.
deleted with VM]) end subgraph U[User-assigned] V2[vm-shared-a] --> I2([uai-shared-identity
independent resource]) V3[vm-shared-b] --> I2 end I2 --> R[(Role assignment
Reader on resource group)] classDef vm fill:#DBEAFE,color:#1E293B classDef id fill:#326CE5,color:#FFFFFF classDef role fill:#F97316,color:#FFFFFF class V1,V2,V3 vm class I1,I2 id class R role
A managed identity compares with a service principal that has a client secret like this:
| Aspect | Service principal with secret | Managed identity |
|---|---|---|
| Credential | A secret or certificate you store and rotate | None, Azure manages it |
| Where it works | Anywhere, including outside Azure | Supported Azure resources |
| Lifecycle | You create, rotate and delete it | Tied to a resource, or standalone |
Creating an identity grants no permissions. Access always comes from an Azure RBAC role assignment, so a new identity can authenticate but cannot do anything until you assign it a role.
Detailed Step-by-Step Practical Lab
Set the variables used throughout the lab.
export RG=rg-identity-lab-indiaexport LOCATION=centralindiaexport SUB_ID=$(az account show --query id --output tsv)- Create the resource group and a VM with a System-Assigned identity:
az group create --name $RG --location $LOCATION az vm create \ --resource-group $RG \ --name vm-system-identity \ --image Ubuntu2204 \ --size Standard_B1s \ --admin-username azureadmin \ --generate-ssh-keys \ --assign-identity- Confirm the identity exists and note its principal ID. This ID is unique to this VM:
az vm show \ --resource-group $RG \ --name vm-system-identity \ --query "identity.principalId" --output tsv- Create a standalone User-Assigned identity and capture its IDs:
export UAI_ID=$(az identity create \ --resource-group $RG \ --name uai-shared-identity \ --query id --output tsv) export UAI_PRINCIPAL=$(az identity show --ids $UAI_ID --query principalId --output tsv)export UAI_CLIENT_ID=$(az identity show --ids $UAI_ID --query clientId --output tsv)The principal ID is used for role assignments, and the client ID is used when requesting tokens.
- Attach that one identity to two different VMs. Pass the full resource ID:
az vm create \ --resource-group $RG --name vm-shared-a \ --image Ubuntu2204 --size Standard_B1s \ --admin-username azureadmin --generate-ssh-keys \ --assign-identity $UAI_ID az vm create \ --resource-group $RG --name vm-shared-b \ --image Ubuntu2204 --size Standard_B1s \ --admin-username azureadmin --generate-ssh-keys \ --assign-identity $UAI_IDTipA VM can hold both kinds at once. Pass
--assign-identity [system] $UAI_IDto enable a System-Assigned identity and attach a User-Assigned one together.
- Confirm both VMs reference the same identity:
az vm show --resource-group $RG --name vm-shared-a \ --query "identity.userAssignedIdentities" --output json az vm show --resource-group $RG --name vm-shared-b \ --query "identity.userAssignedIdentities" --output jsonBoth outputs should show the same uai-shared-identity resource ID, so any role you grant it applies to both VMs.
- Grant the shared identity the Reader role on the resource group. The other VM's System-Assigned identity gets nothing:
export RG_ID=$(az group show --name $RG --query id --output tsv) az role assignment create \ --assignee-object-id $UAI_PRINCIPAL \ --assignee-principal-type ServicePrincipal \ --role Reader \ --scope $RG_ID echo "Client ID: $UAI_CLIENT_ID"echo "Subscription: $SUB_ID"RememberRole assignments can take a few minutes to take effect. If the next step returns an authorization error, wait two or three minutes and try again.
- Connect to
vm-shared-a, request a token for the shared identity, and call the Azure Resource Manager API. ReplaceCLIENT_ID_HEREandSUB_ID_HEREwith the values printed above. Theclient_idparameter is required to pick a specific User-Assigned identity:
az ssh vm --resource-group $RG --name vm-shared-a --local-user azureadmin sudo apt-get update && sudo apt-get install -y jq TOKEN=$(curl -s -H "Metadata:true" \ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/&client_id=CLIENT_ID_HERE" \ | jq -r '.access_token') curl -s -H "Authorization: Bearer $TOKEN" \ "https://management.azure.com/subscriptions/SUB_ID_HERE/resourcegroups/rg-identity-lab-india?api-version=2021-04-01" \ | jq -r '.name'The last command prints rg-identity-lab-india, proving the VM authenticated with no stored credential.
- Now repeat the call from
vm-system-identity, which has an identity but no role. Without aclient_id, the request uses its System-Assigned identity:
az ssh vm --resource-group $RG --name vm-system-identity --local-user azureadmin sudo apt-get update && sudo apt-get install -y jq TOKEN=$(curl -s -H "Metadata:true" \ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" \ | jq -r '.access_token') curl -s -H "Authorization: Bearer $TOKEN" \ "https://management.azure.com/subscriptions/SUB_ID_HERE/resourcegroups/rg-identity-lab-india?api-version=2021-04-01" \ | jq -r '.error.code'The output is AuthorizationFailed. The identity authenticated successfully, but it has no permission, which shows that identity and access are separate things.
- Compare lifecycles. Delete one shared VM and confirm the User-Assigned identity survives:
az vm delete --resource-group $RG --name vm-shared-a --yes az identity show --ids $UAI_ID --query name --output tsvThe identity still exists, and vm-shared-b keeps working. If you deleted vm-system-identity instead, its identity would be removed with it.
- Clean up. Deleting the resource group removes the VMs, the identity and the role assignment together:
az group delete --name $RG --yes --no-waitProduction Best Practices & Common Pitfalls
Common MistakeCreating a service principal with a client secret for a workload that runs on Azure compute such as a VM, App Service or a container app, when a managed identity gives the same access with nothing to store, rotate or leak.
SecurityAny process on a VM can ask the metadata service for that identity's token, and the service does not distinguish between applications. Give the identity only the roles the workload needs, at the narrowest scope that works.
TipUse a User-Assigned identity when several resources need identical permissions, such as a fleet of VMs reading the same Key Vault, or when VMs are recreated often. Use a System-Assigned identity when the access belongs to exactly one resource for its whole life.
- Prefer User-Assigned identities in infrastructure as code. A recreated VM gets a new System-Assigned identity with a new principal ID, so its role assignments must be created again, while a User-Assigned identity keeps its roles.
- Clean up role assignments for deleted identities. Deleting a resource can leave role assignments that show an unknown principal, so remove them to keep access reviews clean.
- Know where managed identities work. They exist on supported Azure compute and on Azure Arc-enabled servers. For code running on a laptop,
DefaultAzureCredentialfalls back to your Azure CLI login, and workloads outside Azure can use workload identity federation instead of a secret. - Use workload identity for Kubernetes pods. On AKS, workload identity ties a Kubernetes service account to an identity, so you can give each pod its own access instead of a whole node.
- Pick the right ID for the job. Use the principal ID for role assignments and the client ID when requesting a token for a specific User-Assigned identity.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
az vm create --assign-identity |
Create a VM with a System-Assigned identity |
az identity create |
Create a standalone User-Assigned identity |
az vm create --assign-identity RESOURCE_ID |
Attach an existing User-Assigned identity |
az vm identity assign --identities RESOURCE_ID |
Add an identity to an existing VM |
az role assignment create --assignee-object-id ID |
Grant an identity a role at a scope |
az role assignment list --assignee ID --all |
Review what an identity can access |
| Error | Cause | Fix |
|---|---|---|
AuthorizationFailed from the API |
Identity has no role at that scope | Create a role assignment and wait a few minutes |
Token request returns Identity not found |
Wrong or missing client_id for a User-Assigned identity |
Pass the identity's client ID |
| Token request times out | Not running on an Azure VM, or no identity attached | Run it on the VM and check identity in az vm show |
| Role assignment shows an unknown principal | The identity or resource was deleted | Delete the stale assignment |
--assign-identity rejects a name |
A short name was passed | Use the full resource ID from az identity show |