Azure Key Vault Client Libraries for Python

4.2.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure Key Vault using `DefaultAzureCredential` and perform basic secret operations: setting, getting, and deleting a secret. Ensure your environment is configured for Azure authentication and you have sufficient permissions on the Key Vault.

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.")

view raw JSON →