Azure Key Vault Secrets Client Library
The Azure Key Vault Secrets client library for Python (version 4.10.0) provides secure storage and management for sensitive information like tokens, passwords, API keys, and certificates. As part of the actively developed Azure SDK for Python, it maintains a regular release cadence with updates typically occurring every few months to introduce new features and improvements.
Common errors
-
ModuleNotFoundError: No module named 'azure.keyvault.secrets'
cause The `azure-keyvault-secrets` package is not installed, or there is a naming conflict (e.g., a local file named `azure.py` or `keyvault.py` shadowing the actual library).fixEnsure the package is correctly installed using `pip install azure-keyvault-secrets`. If the error persists, check your project directory for files or folders named `azure` or `keyvault` that might be causing an import conflict. -
DefaultAzureCredential failed to retrieve a token from the included credentials.
cause The `DefaultAzureCredential` class, which attempts various authentication methods, was unable to obtain an access token. This often happens because necessary environment variables are not set, a managed identity is not correctly configured or assigned, or local developer tools are not authenticated to Azure.fixConfigure appropriate Azure authentication for your environment. For local development, set `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, and `AZURE_CLIENT_SECRET` environment variables. For Azure services (like App Service or Functions), enable and assign a system-assigned or user-assigned managed identity to the resource. -
AccessDenied / Forbidden (403) or User is not authorized to read secrets from '/subscriptions/{resource guid}/resourceGroups/{resourcegroup}/providers/Microsoft.KeyVault/vaults/{keyvaultname}/secrets/{secretname}' resource.cause The identity (user, service principal, or managed identity) attempting to access the Key Vault lacks the necessary data plane permissions (e.g., 'Get', 'List' for secrets) or there's a mismatch in the Key Vault's access model (Azure RBAC vs. Vault Access Policies).fixGrant the required permissions to the identity. If using Azure RBAC (recommended), assign the 'Key Vault Secrets User' role (or 'Key Vault Secrets Officer' for write operations) to the identity at the Key Vault scope. If using Vault Access Policies, ensure an access policy granting 'Get' and 'List' secret permissions is configured for the identity. Verify that the Key Vault's 'Access configuration' setting aligns with your chosen permission model. -
TypeError: string indices must be integers (when trying to get secret value)
cause This error occurs when attempting to access the secret value from the `KeyVaultSecret` object using dictionary-like indexing (e.g., `secret['value']`) instead of the correct attribute access (`.value`).fixAfter retrieving a secret with `client.get_secret('secretName')`, the actual string value of the secret is accessed via the `.value` attribute of the returned `KeyVaultSecret` object, like `secret_object = client.get_secret('mySecretName'); secret_value = secret_object.value`.
Warnings
- breaking The legacy `azure-keyvault` package has been split into specific client libraries: `azure-keyvault-keys`, `azure-keyvault-secrets`, and `azure-keyvault-certificates`. The `azure-keyvault` package no longer contains code and only installs these sub-packages. Direct imports from `azure.keyvault` will fail.
- gotcha Common errors (HTTP 403 Forbidden) are typically due to incorrect permissions. Azure Key Vault uses either Role-Based Access Control (RBAC) or legacy access policies. The authenticated identity (user, service principal, managed identity) must have explicit permissions (e.g., 'Key Vault Secrets User' role or 'Get', 'Set', 'Delete' access policy permissions) for the desired operations.
- gotcha Frequent requests can lead to Key Vault throttling (HTTP 429 Too Many Requests). Key Vault is designed for secure storage, not as a high-throughput runtime database. Avoid fetching secrets on every application request.
- breaking Starting with Azure Key Vault REST API version 2026-02-01 (and corresponding SDKs), Azure RBAC becomes the *default* access control model for *newly created vaults*. While existing vaults retain their current model, deployment scripts creating new vaults might implicitly get RBAC as default, potentially causing `403 Forbidden` errors if RBAC roles are not assigned.
- breaking Support for Python 2.7 has officially ended. This library requires Python 3.9 or later.
- breaking The Key Vault client requires the URL of the Azure Key Vault. This is typically provided via an environment variable (e.g., `KEY_VAULT_URL`) or passed directly to the client constructor, and is essential for initializing the client.
- breaking The script requires the `KEY_VAULT_URL` environment variable to be set, typically to the URL of your Azure Key Vault instance. This variable is crucial for the `SecretClient` to know which Key Vault to connect to.
Install
-
pip install azure-keyvault-secrets azure-identity
Imports
- SecretClient
from azure.keyvault.secrets import SecretClient
- DefaultAzureCredential
from azure.keyvault.secrets import DefaultAzureCredential
from azure.identity import DefaultAzureCredential
- KeyVaultSecret
from azure.keyvault.secrets import KeyVaultSecret
- SecretProperties
from azure.keyvault.secrets import SecretProperties
Quickstart
import os
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
# Retrieve the Key Vault URL from an environment variable
key_vault_url = os.environ.get("KEY_VAULT_URL", "")
if not key_vault_url:
raise ValueError("KEY_VAULT_URL environment variable not set.")
# Authenticate using DefaultAzureCredential, which handles various authentication flows
credential = DefaultAzureCredential()
# Create a SecretClient
secret_client = SecretClient(vault_url=key_vault_url, credential=credential)
secret_name = "MyTestSecret"
secret_value = "mysecretvalue123"
print(f"Setting a secret named '{secret_name}'...")
# Set a secret
set_secret = secret_client.set_secret(secret_name, secret_value)
print(f"Secret set: {{set_secret.name}}, version: {{set_secret.id}}")
print(f"Retrieving the secret named '{secret_name}'...")
# Get a secret
retrieved_secret = secret_client.get_secret(secret_name)
print(f"Secret retrieved: {{retrieved_secret.name}}, value: {{retrieved_secret.value}}")
print(f"Deleting the secret named '{secret_name}'...")
# Delete a secret (soft-delete, if enabled on the vault)
deleted_secret = secret_client.begin_delete_secret(secret_name).result()
print(f"Secret deleted: {{deleted_secret.name}}, recovery ID: {{deleted_secret.recovery_id}}")
print("Done.")