Azure Key Vault Keys Client Library for Python
The `azure-keyvault-keys` library is the Microsoft Azure Key Vault client library for Python, enabling developers to manage cryptographic keys within Azure Key Vault. It facilitates operations such as creating, retrieving, updating, deleting, and listing RSA and Elliptic Curve (EC) keys, including those backed by Hardware Security Modules (HSMs). The library is part of the broader Azure SDK for Python, currently at version 4.11.0, and typically sees a few stable releases per year while being actively maintained.
Warnings
- breaking Python 2.7 and Python 3.6 are no longer supported. Version 4.x.x of `azure-keyvault-keys` requires Python 3.9 or later.
- gotcha The `azure-keyvault` package is a metapackage and no longer contains actual code. Users should install specific client libraries like `azure-keyvault-keys` directly.
- gotcha Incorrect permissions are a common issue. Ensure the authenticated identity (user, service principal, managed identity) has the specific 'List' and 'Get' Key permissions (e.g., 'Key Vault Crypto Officer' role in RBAC or 'Get', 'List' for Keys in access policies) configured for the Key Vault.
- gotcha Reliance on the exact output format of model methods like `as_dict()` (or similar internal representations) can break across minor/patch versions. The SDK team considers changes to private properties or their serialization not a public breaking change.
Install
-
pip install azure-keyvault-keys azure-identity
Imports
- KeyClient
from azure.keyvault.keys import KeyClient
- KeyVaultKey
from azure.keyvault.keys import KeyVaultKey
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.keyvault.keys import KeyClient
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import ResourceNotFoundError
# Retrieve the Key Vault URI from environment variable
# Ensure 'KEY_VAULT_NAME' environment variable is set
# e.g., export KEY_VAULT_NAME="your-unique-keyvault-name"
key_vault_name = os.environ.get("KEY_VAULT_NAME", None)
if not key_vault_name:
raise ValueError("Please set the KEY_VAULT_NAME environment variable.")
KV_URI = f"https://{key_vault_name}.vault.azure.net/"
# Authenticate with DefaultAzureCredential
# This credential type is suitable for most scenarios, including local development and production.
# It attempts to authenticate via environment variables (e.g., AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID),
# managed identity, Azure CLI, etc.
credential = DefaultAzureCredential()
# Create a KeyClient
key_client = KeyClient(vault_url=KV_URI, credential=credential)
key_name = "MyTestKeyPython"
try:
print(f"Creating an RSA key named '{key_name}'...")
# Create an RSA key with a specified size
key = key_client.create_rsa_key(key_name, size=2048)
print(f"Key created: {key.name}, Version: {key.properties.version}")
print(f"Retrieving the key named '{key_name}'...")
retrieved_key = key_client.get_key(key_name)
print(f"Key retrieved: {retrieved_key.name}, Type: {retrieved_key.key_type}")
print(f"Deleting the key named '{key_name}'...")
# begin_delete_key starts a long-running operation, .wait() waits for completion
deleted_key = key_client.begin_delete_key(key_name).wait()
print(f"Key deletion initiated: {deleted_key.name} (Recovery ID: {deleted_key.recovery_id})")
except ResourceNotFoundError:
print(f"Key '{key_name}' not found. It might have been deleted or never existed.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Always close the credential and client when no longer needed
credential.close()
key_client.close() # KeyClient is not explicitly closeable, but credential should be.
print("Credential closed.")