Your deployed Python function reads DB_PASSWORD with os.getenv and receives the real password. On your laptop, func start hands the same code @Microsoft.KeyVault(...) instead. Nothing in the function changed, so the difference is in who resolves the reference: the Azure platform in production, and the local Functions host during development.

This guide explains how platform resolution works, how to configure identity and least-privilege access, why local resolution fails, and how to choose a local strategy that does not tempt you to paste production secrets into local.settings.json.

Table of Contents

  • How Azure resolves a Key Vault reference
  • Configure identity, access, and the reference
  • Why local resolution fails (and how to diagnose it)
  • Choose a local development strategy
  • A resolver that works in both environments
  • Rotate and verify without leaking secrets
  • Conclusion

How Azure resolves a Key Vault reference

A Key Vault reference is an app setting whose value is an instruction, not a secret. The Azure documentation on Key Vault references describes two accepted forms:

@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/db-password) 
@Microsoft.KeyVault(VaultName=myvault;SecretName=db-password) 

The SecretUri form can include a version identifier at the end. If you omit it, the reference follows the latest version of the secret.

At startup and on a refresh cycle, the Azure platform does the following:

  1. Reads the app setting and recognizes the @Microsoft.KeyVault(...) prefix.
  2. Authenticates as the function app's managed identity.
  3. Requests the referenced secret from Key Vault.
  4. Injects the resolved secret value into the process environment.
  5. Lets your Python code read it with os.getenv like any other setting.

Key Vault references use the app's system-assigned identity by default. If you assign a user-assigned identity, you can point reference resolution at it with the keyVaultReferenceIdentity property. In both cases, the function code stays the same and does not need to import the Key Vault SDK.

Two details matter for development:

  • A versionless reference picks up a rotated secret within 24 hours. A configuration change restarts the app and forces an immediate refetch.
  • If a reference cannot be resolved, the platform uses the reference string itself as the setting value. Your code then receives @Microsoft.KeyVault(...) and usually fails somewhere less obvious, such as a database login.

Configure identity, access, and the reference

The example below uses a secret named db-password and an app setting named DB_PASSWORD. Keeping those names stable lets you rotate the secret without changing application code.

First, create a vault that uses Azure RBAC for data-plane authorization:

az keyvault create \ --name <vault-name> \ --resource-group <resource-group> \ --location <region> \ --enable-rbac-authorization true 

Next, enable a system-assigned identity on the function app and capture its principal ID:

principalId=$(az functionapp identity assign \ --name <function-app-name> \ --resource-group <resource-group> \ --query principalId \ --output tsv) 

Grant that identity read access to secrets, scoped to the vault rather than the whole subscription. The Key Vault RBAC guide explains that Key Vault Secrets User can read secret contents but cannot manage them, which is the right level for a runtime identity:

az role assignment create \ --role "Key Vault Secrets User" \ --assignee "$principalId" \ --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.KeyVault/vaults/<vault-name>" 

Create the secret and then point the app setting at it:

az keyvault secret set \ --vault-name <vault-name> \ --name db-password \ --value '<database-password>' az functionapp config appsettings set \ --name <function-app-name> \ --resource-group <resource-group> \ --settings 'DB_PASSWORD=@Microsoft.KeyVault(SecretUri=https://<vault-name>.vault.azure.net/secrets/db-password)' 

local.settings.json is local-only and is not published with the project, so the reference must also exist as an app setting in Azure.

Secret names in Key Vault are more restrictive than app setting names: an object name must be 1 to 127 characters and can contain only letters, digits, and hyphens, as the Key Vault objects overview explains. That is why the setting DB_PASSWORD points to the secret db-password, not to another underscore name.

Role assignments and identity changes are not always instant. If the app still shows the literal reference, give propagation a few minutes before changing code.

Why local resolution fails (and how to diagnose it)

In Azure, the App Service platform resolves the reference. Locally, that platform layer is absent, and your laptop has no managed identity. Core Tools v4 contains a separate local resolver, but it does not use the function app's identity and has a history of failing quietly.

A 2026 issue in the Azure Functions Core Tools repository explains the problem well: local Key Vault reference support was introduced in earlier releases and ported to v4, but a later change made resolution failures non-blocking, so a failed lookup can leave the literal reference in the environment with no visible error (Core Tools issue #4845). The function host starts normally, and the failure appears only when your code tries to use the value.

Common causes include:

  • You are not signed in to Azure, or az login is pointing at the wrong tenant or subscription.
  • Your user account has no data-plane read access to the vault.
  • The vault is network-restricted and your laptop's address is not allowed.
  • The reference has a typo, the vault name is wrong, or a pinned secret version no longer exists.
  • You are running Core Tools v5 preview. An open issue reports that v5 does not resolve Key Vault references from local.settings.json at all, while the reporter saw v4 substitute the value (Core Tools issue #5676).

Start with the tool version and your signed-in identity:

func --version az account show --query "{tenant:tenantId, subscription:name}" --output table 

Then test whether your own identity can read the secret without printing its value:

az keyvault secret show \ --vault-name <vault-name> \ --name db-password \ --query id \ --output tsv 

A 403 here means the local failure is an access problem, not a Python problem. A successful read points to the tool version, the reference string, or the identity the host is actually using.

Finally, make the failure visible in code without logging the secret:

import os raw = os.getenv("DB_PASSWORD", "") print({ "present": bool(raw), "unresolved": raw.startswith("@Microsoft.KeyVault("), }) 

If unresolved is True, the host did not replace the reference. That is the signal to stop debugging your database connection and fix the configuration layer.

Choose a local development strategy

Before choosing, it helps to separate configuration from secret retrieval. The environment variables and secrets section of this Python Azure Functions guide walks through how settings become environment variables in both environments, which makes the trade-offs below easier to judge.

Strategy What local.settings.json holds What the code does Best for Main trade-off
Placeholder A fake value such as local-not-a-real-password Reads the environment only Unit tests and work that never calls the real dependency Does not exercise real authentication
Development vault plus DefaultAzureCredential The dev vault URI, plus a reference or no secret value Fetches with SecretClient Integration testing against real Key Vault Extra vault, role assignment, and developer sign-in
Direct SDK everywhere The vault URI Always fetches with SecretClient Per-tenant vaults and secrets that change at runtime SDK calls on the hot path, caching, no platform refresh

Placeholder values are the lowest-effort option, but only when the local code path does not need the real secret. Use an obviously invalid value so an accidental real call fails loudly, and never paste a production password into the file. Microsoft's local development guidance notes that local.settings.json may contain secrets and should not be committed to source control.

A dedicated development vault gives you the most realistic local behavior without exposing production. Create a separate vault for development, store dev-only secrets there, and grant your developer account Key Vault Secrets User on that vault. Put only the vault URI in local.settings.json:

{ "IsEncrypted": false, "Values": { "FUNCTIONS_WORKER_RUNTIME": "python", "KEY_VAULT_URI": "https://<dev-vault-name>.vault.azure.net" } } 

Your code then uses SecretClient with DefaultAzureCredential. The DefaultAzureCredential documentation explains that the credential tries managed identity in Azure and developer sign-ins such as the Azure CLI locally, so one code path works in both places. The Key Vault Python quickstart shows the client construction and get_secret call.

Direct SDK fetches everywhere means you stop using Key Vault references entirely. This is the right choice when the vault or secret name depends on the request, or when you need a rotation to take effect immediately. The cost is that every function instance must authenticate and fetch, so you need a cache with a TTL and should watch cold-start latency and Key Vault throttling.

For a stable database password, the practical combination is: references in Azure, a development vault with DefaultAzureCredential locally, and placeholders only in unit tests. Relying on Core Tools to resolve references locally can work, but pin the tool version and do not treat that behavior as a contract.

A resolver that works in both environments

The following helper treats an unresolved reference as a signal to fetch the secret directly. In Azure, a working Key Vault reference arrives as a normal value and returns immediately. Locally, the literal reference (or a missing setting) triggers a Key Vault call using your developer identity.

Install the two packages it needs:

azure-identity azure-keyvault-secrets 
import logging import os import time from functools import lru_cache from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient REFERENCE_PREFIX = "@Microsoft.KeyVault(" CACHE_TTL_SECONDS = 300 logger = logging.getLogger(__name__) _secret_cache: dict[tuple[str, str], tuple[float, str]] = {} @lru_cache(maxsize=4) def _client(vault_uri: str) -> SecretClient: return SecretClient( vault_url=vault_uri, credential=DefaultAzureCredential(), ) def get_setting(setting_name: str, secret_name: str) -> str: value = os.getenv(setting_name) if value and not value.startswith(REFERENCE_PREFIX): logger.info("Resolved %s from the environment", setting_name) return value vault_uri = os.getenv("KEY_VAULT_URI") if not vault_uri: raise RuntimeError( f"{setting_name} is unresolved and KEY_VAULT_URI is not set" ) cache_key = (vault_uri, secret_name) now = time.monotonic() cached = _secret_cache.get(cache_key) if cached and now - cached[0] < CACHE_TTL_SECONDS: logger.info("Resolved %s from the Key Vault cache", setting_name) return cached[1] secret = _client(vault_uri).get_secret(secret_name).value _secret_cache[cache_key] = (now, secret) logger.info("Resolved %s from Key Vault", setting_name) return secret 

Use it where the secret is needed:

db_password = get_setting("DB_PASSWORD", "db-password") 

The behavior in each environment is deliberate:

  • Azure, reference resolved: DB_PASSWORD is already the secret, so the helper returns it and makes no Key Vault call.
  • Azure, reference broken: the helper attempts a direct SDK fetch with the same managed identity. A typo or platform-side problem may be bypassed, while a permission problem will fail with a clearer error. Either way, the log line says Key Vault, not environment, so check the reference resolution status in the portal.
  • Local, developer signed in: the helper reads the dev vault through DefaultAzureCredential.
  • Local, placeholder set: the first branch returns the placeholder. That is fine for tests and dangerous for anything that talks to a real service.

The 300-second cache is a compromise: short enough to see a rotation during development, long enough to avoid a Key Vault round trip on every invocation. The platform reference path in Azure still follows its own 24-hour refresh cycle, so the cache only affects the fallback path.

If you use a user-assigned identity, set AZURE_CLIENT_ID to its client ID so DefaultAzureCredential knows which identity to use. Without it, the credential defaults to the system-assigned identity.

Rotate and verify without leaking secrets

Use this checklist when the function moves from a local vault to production:

  • Keep names stable. The app setting DB_PASSWORD and the secret db-password should not change when the password changes. Add a new secret version instead, and let a versionless reference follow it.
  • Do not pin versions by accident. A versioned SecretUri stays on that version until you update the app setting. Pin only when you intentionally want a rollback point.
  • Scope the role to the vault. Grant the runtime identity Key Vault Secrets User at the vault scope. Keep Key Vault Secrets Officer for the deployment or operations identity that creates secrets, not for the function app.
  • Use one vault per environment. Production and development secrets should not share a vault, and app settings that differ by environment should be marked as slot settings if you use deployment slots.
  • Verify resolution in Azure. In the portal, open the app setting and select Edit; the dialog shows the resolution status or an error. The Key Vault Application Settings Diagnostics detector provides more detail when the status is not obvious.
  • Never log the value. Log the setting name, the vault name, and whether the value came from the environment or Key Vault. Do not log the first characters of a secret as a debugging aid.
  • Test a rotation in development. Add a new version of db-password in the dev vault, wait for the cache TTL or restart the function, and confirm the function still works. Assert on behavior, not on the secret string.
  • Test the failure path. Remove your own read access in the dev vault and confirm the function returns a clear error instead of silently using the literal reference.

Conclusion

Key Vault references are resolved by the Azure platform through the function app's managed identity, which is why os.getenv is all the code needs in production. Local development has a different resolver with different credentials, and its failures are easy to miss because the literal reference is a valid string.

Configure the system-assigned identity and a vault-scoped Key Vault Secrets User role, keep the app setting name and secret name stable, and use a development vault with DefaultAzureCredential for local runs. Add the prefix check so an unresolved reference is obvious, and reserve placeholders for tests that never touch a real service.