Azure Key Vault Secrets Client Library

4.10.0 · active · verified Sun Mar 29

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.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure Key Vault using `DefaultAzureCredential` and perform basic secret operations: setting a secret, retrieving it, and initiating its deletion. Ensure you have the `KEY_VAULT_URL` environment variable set to your Key Vault's URI (e.g., `https://<your-keyvault-name>.vault.azure.net`). Your identity must have appropriate permissions (e.g., 'Key Vault Secrets User' RBAC role or 'Get', 'Set', 'Delete' permissions via access policies) to perform these operations.

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

view raw JSON →