Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 25 of 28
❮Prev Next❯

Azure Key Vault: Retrieve and Rotate Secrets

Module 4: Secure & Monitor ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Create a secret, look at its versions and set an expiry date Create a secret, look at its versions and set an expiry date.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Open <strong>Key vaults</strong> and select <strong>+ Create</strong>.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Open Key vaults and select + Create.
    2. Soft-delete is always on. Purge protection stops anyone, even you, from permanently deleting secrets early.
    3. Use Azure RBAC. Give apps Key Vault Secrets User and yourself Key Vault Secrets Officer.
    4. Review and Create.
    5. Open Objects → Secrets → + Generate/Import. Set an expiration date so you get warned before the secret goes stale.
    6. Each change makes a new version. A URI without a version always returns the current one, so apps pick up rotations on their own.
    7. 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.

    😟 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
    🛠️ Solved with: Azure Key Vault

    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.

    ▶ Explainer video See it in motion 8 steps · 1 min 57 sec

    An animation of a chat API whose model key is pushed to a public GitHub repo, then fixed: the app gets a managed identity, Microsoft Entra ID issues it a token, Key Vault checks the Key Vault Secrets User role and returns the secret, each write stacks a new secret version that apps read as latest, and a SecretNearExpiry event goes through Event Grid to a rotation function that writes a new version.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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.
    8. 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 typeWhat it isWhen to pick it
    System-assigned managed identityCreated with the resource and deleted with it. One per resource.One app, its own access. The simplest choice.
    User-assigned managed identityA 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.

    RoleCan doGive it to
    Key Vault Secrets UserRead secret valuesThe running app
    Key Vault Secrets OfficerCreate, update, delete, recover secrets (not change permissions)A rotation function, a release pipeline
    Key Vault ReaderSee metadata, not valuesAuditors, dashboards
    Key Vault AdministratorEverything on data in the vaultAdmins 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_secret makes 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_before and expires_on when 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. 1 Expiry set

      The secret has expires_on, for example 90 days out.

    2. 2 Event

      Key Vault publishes Microsoft.KeyVault.SecretNearExpiry 30 days before.

    3. 3 Function

      An Event Grid triggered function with Secrets Officer makes a new credential at the source.

    4. 4 New version

      It calls set_secret with the new value and a new expiry.

    5. 5 Apps refresh

      Apps that read the latest version pick it up on their next refresh.

    Rotating a secret with Event Grid and a function

    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

    Customer service software

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    A Python web app that runs in Azure Container Apps must read an API key from Azure Key Vault. No credentials can be stored in the code, the image, or the app configuration. What should you use to authenticate the app to Key Vault?

    Question 2

    Question 2 of 5

    A vault uses the Azure RBAC permission model. An app's managed identity must be able to read secret values and must not be able to create, update, or delete secrets. Which role should you assign to the identity at the vault scope?

    Question 3

    Question 3 of 5

    A developer uses the following code: client = SecretClient(vault_url=url, credential=DefaultAzureCredential()). The secret named db-password has been updated four times.

    Which method should the developer call to retrieve the creation date and enabled state of every version of db-password?

    Question 4

    Question 4 of 5

    A database password is stored as a Key Vault secret with an expiration date. You must automatically run code that generates a new password and stores it as a new secret version before the current password expires. The solution must minimize custom polling. What should you implement?

    Question 5

    Question 5 of 5 · Select 2

    You are configuring a Key Vault that stores production secrets. Which TWO statements about soft delete and purge protection are true?

    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. 1.Which Python package contains SecretClient?Show

      azure-keyvault-secrets.

    2. 2.Which method lists every version of one secret?Show

      list_properties_of_secret_versions.

    3. 3.Which role should a web app get to read secret values?Show

      Key Vault Secrets User.

    4. 4.Can you turn off purge protection after enabling it?Show

      No.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.