Azure Key Vault: Retrieve and Rotate Secrets
30-second answer
Azure Key Vault keeps secrets such as API keys and connection strings out of your code. Your app signs in with a managed identity through DefaultAzureCredential, needs the Key Vault Secrets User role, and reads the value with SecretClient.get_secret(). Every set_secret() creates a new version, so rotation means writing a new version (often from a function triggered by the Event Grid SecretNearExpiry event) while apps that ask for the latest version pick it up without a redeploy.
Exam objective: 4.1.1 Secure secrets by using Azure Key Vault, including rotation and retrieval. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Open <strong>Key vaults</strong> and select <strong>+ Create</strong>.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Open Key vaults and select + Create.
- Soft-delete is always on. Purge protection stops anyone, even you, from permanently deleting secrets early.
- Use Azure RBAC. Give apps Key Vault Secrets User and yourself Key Vault Secrets Officer.
- Review and Create.
- Open Objects → Secrets → + Generate/Import. Set an expiration date so you get warned before the secret goes stale.
- Each change makes a new version. A URI without a version always returns the current one, so apps pick up rotations on their own.
- Secrets rotate through events: 30 days before expiry Key Vault raises SecretNearExpiry, and a function writes a new version. The Rotation policy blade is for keys only.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Secrets don’t belong in code
A connection string in config.py ends up in git, in screenshots and in old laptops. Azure Key Vault stores secrets, keys and certificates. The app reads them at run time with a managed identity, so there’s no password to steal.
🤔 What happens if…
Read this tour as text
- Secrets don’t belong in code. A connection string in
config.pyends up in git, in screenshots and in old laptops. Azure Key Vault stores secrets, keys and certificates. The app reads them at run time with a managed identity, so there’s no password to steal. - Versions and rotation. Each time you set a secret, Key Vault keeps a new version. Apps that ask for the secret without a version get the latest. Rotation creates a new version: for keys, a rotation policy does it on a schedule; for secrets, Key Vault raises a
SecretNearExpiryevent through Event Grid and your function sets the new value. Apps pick it up without a redeploy. - App Configuration. Azure App Configuration holds settings as key-values with optional labels (dev, prod) and feature flags. It can point at Key Vault with Key Vault references. Apps refresh settings without restarting, often by watching a sentinel key.
- A trace across services. One user question goes web API → queue → worker → Cosmos DB → model. OpenTelemetry gives every hop a span that shares one trace ID, so you see the whole journey. The Azure Monitor OpenTelemetry Distro sends it to Application Insights.
- Find the slow span. The trace shows each span’s duration. Here the model call is fine, but a Cosmos DB query without a partition key takes 2.4 seconds. Custom spans and attributes (like
tenant.id) make the story even clearer. - Logs live in tables. Application Insights and Log Analytics store telemetry in tables:
requests,dependencies,exceptions,traces, plus metrics. Container Apps logs land inContainerAppConsoleLogs_CL, AKS inContainerLogV2. - Ask with KQL. Kusto Query Language (KQL) reads top to bottom through pipes:
requests | where success == false | summarize count() by bin(timestamp, 5m) | render timechart.wherefilters,summarizeaggregates,projectpicks columns,joincombines tables. - Turn a query into an alert. A log search alert runs a KQL query on a schedule and fires when the result crosses a threshold. A metric alert watches a number like CPU or queue length. Either can email the team or call a webhook.
Keep the Cosmos DB key out of code and out of app settings. Store it in an RBAC vault, let a web app read it through a Key Vault reference, then load settings, labels and a feature flag from App Configuration.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
A model API key was pushed to GitHub and abused overnight.
😊 THE SOLUTION
Keep secrets in Key Vault and read them with a managed identity.
- Secrets in code✓ Key Vault + managed identity
- Keys never change✓ Rotation policy
- Who read it?✓ Audit logs
Start with a question
Your model API key was in a config file. Someone pushed it to a public GitHub repo. What now?
By morning there’s a bill for thousands of model calls you never made. Bots scan public repos for keys within minutes, so “we’ll fix it later” doesn’t work.
The fix isn’t just “delete the commit”. The key shouldn’t have been in the code at all. Azure Key Vault holds it instead, and your app asks for it at run time using an identity Azure gives it. There’s no password in the repo, nothing to leak, and when the key changes, the app gets the new one on its own.
Explain it like I’m 10
Visual: Key Vault secrets in motion
See why a key in code leaks, how a managed identity gets the secret instead, and how a new version rolls out on rotation.
Read the video script
- A key in code gets leakedHere's how it usually goes wrong. The model API key sits right in the code. Someone pushes to a public GitHub repo, and bots that scan for keys find it within minutes.
- Give the app an identity insteadSo take the key out. Turn on a managed identity, and Azure gives the app its own identity. In code you just create a DefaultAzureCredential. There's no secret left in the repo to leak.
- Entra ID hands over a tokenWhen the app needs the key, its identity asks Microsoft Entra ID for a token. No password goes over the wire. Azure handles the identity's credentials for you.
- Key Vault checks the roleThe app shows that token to Key Vault. Key Vault checks Azure RBAC. The app has Key Vault Secrets User, which lets it read secret values and nothing more.
- The secret comes backAccess granted. get secret returns the value, and the app keeps it in memory, so it isn't calling the vault on every single request.
- Every write is a new versionEvery time you set a secret, Key Vault stacks a new version on top. The old one stays. Apps that ask for the latest pick up the new value next time they refresh. Pin a version, and rotation never reaches you.
- Near expiry? An event firesGive the secret an expiry date. Thirty days before it, Key Vault publishes a Secret Near Expiry event. Event Grid delivers it to a function that has the Secrets Officer role.
- The function writes v3The function makes a fresh key at the source and saves it as version three. The app picks it up on its next refresh, with no redeploy. Keys in Key Vault have a built-in rotation policy. Secrets don't, so this event and function is how you rotate them.
The technical explanation
Key Vault stores three kinds of things: secrets (any string up to 25 KB, like a connection string or an API key), keys (cryptographic keys for encryption and signing) and certificates. For AI-200 you’ll mostly read and rotate secrets from code.
Who’s allowed in: identities and roles
Your app needs two things to read a secret: an identity, and permission for that identity.
| Identity type | What it is | When to pick it |
|---|---|---|
| System-assigned managed identity | Created with the resource and deleted with it. One per resource. | One app, its own access. The simplest choice. |
| User-assigned managed identity | A standalone Azure resource you attach to one or more resources. | Several apps share the same access, or the role must exist before the app does. |
Permission comes from Azure RBAC, the recommended permission model for Key Vault. The older vault access policies still work, but they can’t be scoped to a single secret and they’re managed outside the normal role system.
| Role | Can do | Give it to |
|---|---|---|
| Key Vault Secrets User | Read secret values | The running app |
| Key Vault Secrets Officer | Create, update, delete, recover secrets (not change permissions) | A rotation function, a release pipeline |
| Key Vault Reader | See metadata, not values | Auditors, dashboards |
| Key Vault Administrator | Everything on data in the vault | Admins only |
# Give the web app's system-assigned identity read access to secrets in one vault
az role assignment create \
--role "Key Vault Secrets User" \
--assignee <principal-id-of-the-app> \
--scope $(az keyvault show -n kv-tailspin-prod --query id -o tsv)
Read, write and list versions in Python
pip install azure-keyvault-secrets azure-identity
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
# In Azure this uses the managed identity; on your laptop it uses az login
credential = DefaultAzureCredential()
client = SecretClient(vault_url=os.environ["KEY_VAULT_URL"], credential=credential)
# Read the latest version
secret = client.get_secret("openai-api-key")
print(secret.name, secret.properties.version) # never print secret.value in real code
# Write a new value: this creates a NEW version, the old one stays
client.set_secret("openai-api-key", "sk-new-value", content_type="text/plain")
# See every version of one secret
for props in client.list_properties_of_secret_versions("openai-api-key"):
print(props.version, props.created_on, props.enabled, props.expires_on)
KEY_VAULT_URL looks like https://kv-tailspin-prod.vault.azure.net/. For a user-assigned identity, tell the credential which one to use with DefaultAzureCredential(managed_identity_client_id="<client-id>") or the AZURE_CLIENT_ID environment variable.
Versions, expiry and deleting safely
- Versions. Each
set_secretmakes a new version with its own ID.get_secret(name)returns the latest;get_secret(name, version)returns a specific one. If your config pins a version, rotation never reaches you, so don’t pin unless you mean it. - Activation and expiry. You can set
not_beforeandexpires_onwhen you write a secret. They’re metadata: Key Vault still returns the value, but the dates drive events and tell your tooling what’s stale. - Soft delete. Always on. A deleted secret stays recoverable for the retention period (7 to 90 days, 90 by default) with
begin_recover_deleted_secret. - Purge protection. Optional. While it’s on, nobody can purge a deleted secret or vault before retention ends, not even an admin. You can’t turn it off once enabled.
Rotation
Keys have a built-in rotation policy: you set “rotate 30 days before expiry” or “every 90 days” and Key Vault creates the new key version itself. Secrets don’t, because only you know how to make a new database password or API key. So secret rotation is event-driven:
-
1 Expiry set
The secret has expires_on, for example 90 days out.
-
2 Event
Key Vault publishes Microsoft.KeyVault.SecretNearExpiry 30 days before.
-
3 Function
An Event Grid triggered function with Secrets Officer makes a new credential at the source.
-
4 New version
It calls set_secret with the new value and a new expiry.
-
5 Apps refresh
Apps that read the latest version pick it up on their next refresh.
Key Vault also publishes SecretNewVersionCreated and SecretExpired, which are handy for telling apps to refresh their cache or for alerting.
Cache what you read
Key Vault throttles a vault that gets too many requests. Don’t call get_secret on every HTTP request. Read the secret at startup, keep it in memory, and refresh on a timer (say every few hours) or when the downstream service rejects the old value. If you run on App Service, Functions or Container Apps, Key Vault references in app settings do this for you.
Architect level Two-credential rotation for zero downtime
If a database has only one password, there’s a gap between “changed in the database” and “every app has the new one”. Services such as Azure Storage and Cosmos DB give you two keys for exactly this reason. The rotation function regenerates the key that isn’t in use, stores it as the new secret version, and on the next rotation flips to the other one. Apps that still hold the previous version keep working until their cache refreshes. Microsoft’s rotation tutorials ship this dual-credential pattern as a function you can deploy.
Real-world business scenario
Tailspin Support (fictional)
- The problem
- A support chatbot kept its model API key and Cosmos DB key in app settings. The keys never changed because nobody knew which of nine services would break.
- What they used
- Azure Key Vault with RBAC, a system-assigned managed identity per container app with Key Vault Secrets User, expiry dates on every secret and an Event Grid triggered function with Secrets Officer that rotates the Cosmos DB key.
- Why that choice
- Each app reads the latest secret version and caches it for a few hours, so rotation doesn't need a redeploy, and every read shows up in the vault's audit log.
- The result
- Keys now rotate every 90 days on their own, and the security team can see exactly which identity read which secret.
When to use it and when not to
✓ Use it when…
- API keys, connection strings, passwords and certificates your app needs at run time.
- Secrets that must rotate without redeploying the apps that use them.
- You need an audit trail of who read a secret and when.
✕ Think twice when…
- Plain settings like a model deployment name or a timeout. Put those in App Configuration.
- A service that supports Microsoft Entra ID sign-in directly. Use the managed identity there and skip the secret entirely.
↔ Alternatives to consider
- Azure App Configuration with Key Vault references, to keep settings and secret pointers in one place.
- Key Vault references in App Service or Functions app settings when you want no SDK code at all.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner Why would you move a connection string from app settings into Key Vault?
Model answer
Because app settings get copied around: into screenshots, pipeline logs and other people's laptops. In Key Vault the value sits in one place, every read is authorised by Microsoft Entra ID and logged, and I can rotate it without touching the app.
Interviewer follows up
And how does the app authenticate to Key Vault without a password?
You
With a managed identity. The app uses DefaultAzureCredential, which picks up the identity in Azure and my az login locally. I give that identity the Key Vault Secrets User role on the vault.
Intermediate What's the difference between Key Vault Secrets User and Key Vault Secrets Officer?
Model answer
Secrets User can read secret values, which is all a running app needs. Secrets Officer can also create, update, delete and recover secrets, so it fits a rotation function or an admin, not the web app.
Experienced developer How would you rotate a database password stored as a Key Vault secret without downtime?
Model answer
I'd set an expiry date on the secret and subscribe a function to the SecretNearExpiry event through Event Grid. The function generates a new password on the database, writes it with set_secret, which creates a new version, and then the old credential is retired after apps have refreshed. A common pattern keeps two credentials and alternates them so there's never a moment with no valid password.
Interviewer follows up
How do the apps notice the new version?
You
They ask for the secret without a version, so they always get the latest. I cache the value in memory and refresh it on a timer, or when a call fails with an authentication error.
Scenario A developer deleted a production secret by mistake. What can you do?
Model answer
Soft delete is always on, so the secret is in a deleted state, not gone. Someone with recover permission (Secrets Officer covers it) can call begin_recover_deleted_secret. If purge protection is on, nobody could have purged it early either.
Architecture & design When would you choose a user-assigned managed identity over a system-assigned one?
Model answer
When several resources need the same access, or when I want the role assignment to exist before the resource is created, for example in a blue-green deployment. A user-assigned identity is its own resource, so it survives when the app is deleted. In code I pass its client ID to DefaultAzureCredential.
Quick revision
Key points
- Key Vault stores secrets, keys and certificates. Apps read secrets at run time.
- SecretClient(vault_url, credential) with DefaultAzureCredential: get_secret, set_secret, list_properties_of_secret_versions.
- Use Azure RBAC (Key Vault Secrets User for apps, Secrets Officer for rotation) rather than legacy access policies.
- Every set_secret creates a new version. No version in the request returns the latest.
- Soft delete is always on. Purge protection is optional and can't be switched off once enabled.
- Secrets rotate through an expiry date, the Event Grid SecretNearExpiry event and a function. Keys have a built-in rotation policy.
Important terminology
- Azure Key Vault
- A managed service that stores secrets, keys and certificates and controls who can read them.
- SecretClient
- The class in the azure-keyvault-secrets Python package that gets, sets, lists and deletes secrets in one vault.
- Managed identity
- An identity in Microsoft Entra ID that Azure gives to a resource, so the app can get tokens without a stored password.
- Key Vault Secrets User
- An Azure RBAC role that lets an identity read secret values, and nothing more.
- Secret version
- An immutable copy of a secret's value. Each set_secret call creates a new one, and a request without a version returns the latest.
- Soft delete
- A Key Vault feature, always on, that keeps a deleted vault or secret recoverable for 7 to 90 days.
- Purge protection
- An optional vault setting that blocks permanent deletion until the soft-delete retention period ends. Once on, it can't be turned off.
- SecretNearExpiry
- The Event Grid event Key Vault publishes 30 days before a secret's expiry date, used to start rotation.
Common mistakes
- Giving the app Key Vault Reader and wondering why get_secret fails. Reader sees metadata, not values.
- Calling get_secret on every request instead of caching, and getting throttled.
- Pinning a secret version in app config, so rotation never reaches the app.
Exam tips
- "Read secrets with no credentials in code" = managed identity + DefaultAzureCredential.
- "Least privilege for an app that only reads secrets" = Key Vault Secrets User.
- "Run code when a secret is about to expire" = Event Grid SecretNearExpiry event.
- "Stop anyone permanently deleting a secret early" = purge protection.
Five quick revision questions
-
1.Which Python package contains SecretClient?Show
azure-keyvault-secrets.
-
2.Which method lists every version of one secret?Show
list_properties_of_secret_versions.
-
3.Which role should a web app get to read secret values?Show
Key Vault Secrets User.
-
4.Can you turn off purge protection after enabling it?Show
No.
-
5.Which object has automatic rotation built in, keys or secrets?Show
Keys, through a rotation policy. Secrets rotate with Event Grid and your own code.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Azure App Configuration: Settings and Feature Flags
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.