Overview and What You Will Learn
Azure Key Vault is a managed service for storing secrets, keys and certificates, with access controlled by Microsoft Entra ID and every access logged. A Managed Identity is an identity that Azure creates and rotates for a resource such as a VM, so the application can authenticate without any stored credential. In this lab, you will create a Key Vault that uses Azure role-based access control, store a secret, give a VM's Managed Identity read-only access, and retrieve the secret from that VM at runtime.
- Creating a Key Vault with Azure RBAC authorization
- Storing and reading a secret
- Enabling a System-Assigned Managed Identity on a VM
- Granting least-privilege access with the Key Vault Secrets User role
- Retrieving a secret through the Instance Metadata Service and through an SDK
- Protecting a vault with soft delete and purge protection
Why This Matters in Production
A developer at a fintech company like Razorpay hardcodes a database password in a config file and commits it. Months later the repository is made public by accident, and every credential in it has to be treated as compromised and rotated under pressure. With Key Vault and Managed Identity, the application fetches the secret at runtime, the repository holds nothing sensitive, and rotating the password means changing one value in the vault.
Core Principles
The secure pattern is not just putting a password in a vault. It is that the caller proves who it is with an identity Azure manages, and the vault checks that identity's permissions on every request. No client secret or certificate exists on the VM to be copied or leaked.
Key Vault supports two permission models. Azure RBAC is the current recommended model, and it uses roles such as Key Vault Secrets User assigned at a chosen scope. The older vault access policy model manages permissions inside each vault separately. This lab uses RBAC.
A System-Assigned identity is tied to one resource and is deleted with it. A User-Assigned identity is a separate resource that several VMs can share, which suits fleets that need identical access.
Detailed Step-by-Step Practical Lab
Set the variables used throughout the lab. Vault names are globally unique and must be 3 to 24 characters.
export RG=rg-keyvault-lab-indiaexport LOCATION=centralindiaexport KV_NAME=kv-lab-mum-$RANDOM- Create the resource group and a Key Vault that uses Azure RBAC:
az group create --name $RG --location $LOCATION az keyvault create \ --name $KV_NAME \ --resource-group $RG \ --location $LOCATION \ --enable-rbac-authorization true- Give yourself permission to write secrets. Owning the resource group is not enough, because RBAC separates management actions from secret data access:
export KV_ID=$(az keyvault show --name $KV_NAME --query id --output tsv)export MY_ID=$(az ad signed-in-user show --query id --output tsv) az role assignment create \ --assignee-object-id $MY_ID \ --assignee-principal-type User \ --role "Key Vault Secrets Officer" \ --scope $KV_ID- Store a secret. This value is a dummy for the lab:
az keyvault secret set \ --vault-name $KV_NAME \ --name sql-connection-string \ --value "Server=tcp:mumbai-prod-sql.database.windows.net;Database=orders;User Id=orders_app;Password=Lab-Only-Pa55"RememberRole assignments can take a few minutes to take effect. If a command returns
Forbiddenright after you assign a role, wait two or three minutes and retry.
- Create a VM with a System-Assigned Managed Identity:
az vm create \ --resource-group $RG \ --name vm-app-lab \ --image Ubuntu2204 \ --size Standard_B1s \ --admin-username azureadmin \ --generate-ssh-keys \ --assign-identityThe --assign-identity flag gives the VM its own identity, which Azure deletes automatically when the VM is deleted.
- Grant that identity read-only access to secrets in this vault only:
export IDENTITY_ID=$(az vm show \ --resource-group $RG \ --name vm-app-lab \ --query identity.principalId --output tsv) az role assignment create \ --assignee-object-id $IDENTITY_ID \ --assignee-principal-type ServicePrincipal \ --role "Key Vault Secrets User" \ --scope $KV_IDThe Key Vault Secrets User role allows reading secret values and nothing else. Scoping it to the vault means the identity cannot read secrets in any other vault.
- Connect to the VM and install
jq:
az ssh vm --resource-group $RG --name vm-app-lab --local-user azureadmin sudo apt-get update && sudo apt-get install -y jq- From the VM, ask the Instance Metadata Service for a token, then call the vault. Replace
KV_NAME_HEREwith your vault name. The address169.254.169.254is reachable only from inside the VM, and no credential file is involved:
TOKEN=$(curl -s -H "Metadata:true" \ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net" \ | jq -r '.access_token') curl -s -H "Authorization: Bearer $TOKEN" \ "https://KV_NAME_HERE.vault.azure.net/secrets/sql-connection-string?api-version=7.4" \ | jq -r '.value'The second command prints the connection string. The token stays in a shell variable and is never written to disk.
- Real applications should use an SDK, which handles tokens and caching. This Python example uses
DefaultAzureCredential, which picks up the VM's Managed Identity automatically:
sudo apt-get install -y python3-pippip install azure-identity azure-keyvault-secrets python3 - << 'EOF'from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClient client = SecretClient( vault_url="https://KV_NAME_HERE.vault.azure.net", credential=DefaultAzureCredential(),)print(client.get_secret("sql-connection-string").value)EOF- Exit the VM, then clean up. Key Vault soft delete keeps a deleted vault, and its name, reserved for the retention period, so purge it if you want to reuse the name:
az group delete --name $RG --yes --no-wait # after the group is gone:az keyvault purge --name $KV_NAME --location $LOCATIONProduction Best Practices & Common Pitfalls
Common MistakeReading a secret once and pasting the value into application config "to save an API call." That recreates the leak you were avoiding, and rotating the secret in the vault then changes nothing for the app. Fetch it at startup or on a refresh schedule instead.
SecurityEnable purge protection on every production vault. Soft delete is on by default and lets you recover deleted secrets, but without purge protection someone with permission can permanently purge them. Purge protection cannot be turned off once enabled, and it holds a deleted vault's name for the retention period.
TipAssign roles at the narrowest scope that works. A role on one vault, or even on one secret, limits the damage if an identity is compromised, whereas a role on a subscription exposes every vault in it.
- Prefer Managed Identity over service principals with stored credentials. A service principal still needs a client secret or certificate saved somewhere, and Managed Identity needs nothing saved.
- Remember that any process on the VM can request the identity's token. The metadata endpoint does not distinguish between applications, so give the identity only the permissions the workload truly needs.
- Choose Azure RBAC over access policies for new vaults. RBAC gives central auditing, conditions, and the same model used by the rest of Azure.
- Turn on diagnostic logging. Send Key Vault audit logs to Log Analytics so you can see who read which secret and when.
- Restrict network access for production vaults. Use the vault firewall or a private endpoint so the data plane is not open to the whole internet.
- Use secret versions and expiry dates. Each
secret setcreates a new version, so applications that read the latest version pick up rotations without a redeploy.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
az keyvault create --enable-rbac-authorization true |
Create a vault that uses Azure RBAC |
az keyvault secret set --vault-name V --name N --value X |
Store or update a secret |
az keyvault secret show --vault-name V --name N |
Read a secret |
az vm create --assign-identity |
Create a VM with a System-Assigned identity |
az role assignment create --role "Key Vault Secrets User" |
Grant read-only secret access |
az keyvault purge --name V |
Permanently remove a soft-deleted vault |
| Error | Cause | Fix |
|---|---|---|
Forbidden or 403 on secret set or get |
Missing data-plane role, or not yet propagated | Assign the right role and wait a few minutes |
Caller is not authorized to perform action |
Identity has a management role but no data role | Assign Secrets Officer or Secrets User |
VaultAlreadyExists |
Vault name taken or soft-deleted | Choose a new name or purge the old vault |
| IMDS call times out | Not running on an Azure VM, or identity not enabled | Run it on the VM and check identity.principalId |
SecretNotFound |
Wrong secret name or vault URL | Check the name and the vault DNS name |