Azure Key Vault Keys Client Library for Python

4.11.0 · active · verified Tue Apr 07

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

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate to Azure Key Vault using `DefaultAzureCredential`, create an RSA key, retrieve it, and then initiate its deletion. Ensure your environment variables for Azure authentication (e.g., `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_TENANT_ID`) are set or that you are logged in via Azure CLI, and `KEY_VAULT_NAME` is configured to point to your Key Vault instance.

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

view raw JSON →