Azure Key Vault Client Libraries for Python
The `azure-keyvault` library provides client access to Azure Key Vault, a cloud service for securely storing and accessing secrets, keys, and certificates. It offers distinct clients for managing each resource type within the unified `azure-keyvault` umbrella package. As part of the Azure SDK for Python (Track 2), it integrates with `azure-identity` for authentication. The current stable version is 4.2.0, with minor updates typically released on a bi-annual basis.
Warnings
- breaking The `azure-keyvault` library (version 4.x) is part of the 'Track 2' Azure SDK for Python. This introduced a complete redesign of the API surface compared to older 'Track 1' libraries (e.g., `azure-keyvault-secrets` < 4.0). Client constructors, method names, and return types are fundamentally different.
- gotcha Azure Key Vault clients are modular. While `azure-keyvault` is a meta-package, you instantiate `SecretClient`, `KeyClient`, and `CertificateClient` from their respective sub-packages (`azure.keyvault.secrets`, `azure.keyvault.keys`, `azure.keyvault.certificates`).
- gotcha Authentication is handled by the `azure-identity` library. Misconfiguration of credentials (e.g., missing environment variables, unauthenticated Azure CLI session) is a common initial hurdle, leading to `ClientAuthenticationError`.
- gotcha All Key Vault client constructors (e.g., `SecretClient`, `KeyClient`) require the `vault_url` parameter, which specifies the URI of your Azure Key Vault instance. This URL typically follows the pattern `https://<your-key-vault-name>.vault.azure.net/`.
Install
-
pip install azure-keyvault -
pip install azure-keyvault-secrets azure-keyvault-keys azure-keyvault-certificates azure-identity
Imports
- SecretClient
from azure.keyvault.secrets import SecretClient
- KeyClient
from azure.keyvault.keys import KeyClient
- CertificateClient
from azure.keyvault.certificates import CertificateClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
# For authentication, ensure you have set up environment variables or Azure CLI login.
# For local development, DefaultAzureCredential will try:
# 1. Environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET)
# 2. Managed Identity
# 3. Azure CLI (e.g., `az login`)
# 4. Azure Developer CLI
# 5. Visual Studio Code
# Get your Key Vault URL from environment variable or replace with your actual URL
key_vault_url = os.environ.get("AZURE_KEYVAULT_URL", "https://your-key-vault-name.vault.azure.net/")
if not key_vault_url:
raise ValueError("AZURE_KEYVAULT_URL environment variable or explicit URL is required.")
# Authenticate using DefaultAzureCredential
credential = DefaultAzureCredential()
# Create a SecretClient
secret_client = SecretClient(vault_url=key_vault_url, credential=credential)
secret_name = "MyTestSecret"
secret_value = "HelloFromPythonSDK"
try:
print(f"Setting secret '{secret_name}'...")
set_secret = secret_client.set_secret(secret_name, secret_value)
print(f"Secret set: Name={set_secret.name}, Value={set_secret.value}")
print(f"Getting secret '{secret_name}'...")
retrieved_secret = secret_client.get_secret(secret_name)
print(f"Secret retrieved: Name={retrieved_secret.name}, Value={retrieved_secret.value}")
print(f"Deleting secret '{secret_name}'...")
# Poller for long-running operation, often involved in deletion
poller = secret_client.begin_delete_secret(secret_name)
deleted_secret = poller.result() # Wait for deletion to complete
print(f"Secret deleted: Name={deleted_secret.name}")
except Exception as e:
print(f"An error occurred: {e}")
print("Ensure you have set AZURE_KEYVAULT_URL and authenticated (e.g., via `az login`).")
print("Also ensure the authenticated principal has 'Get', 'Set', and 'Delete' secret permissions on the Key Vault.")