Azure Key Vault Certificates Client Library for Python
The Azure Key Vault Certificates client library for Python allows developers to manage X.509 certificates in Azure Key Vault. It provides capabilities to create, retrieve, update, and delete certificates, as well as manage certificate issuers, contacts, and policies. Azure Key Vault is a cloud service for securely storing and managing secrets, keys, and certificates. This library is part of the Azure SDK for Python and is currently at version 4.10.0, with active development and regular updates.
Common errors
-
Forbidden (403)
cause The identity (user, service principal, or managed identity) attempting to access the Key Vault does not have the necessary permissions assigned through Azure RBAC or Key Vault access policies to perform the requested certificate operation.fixGrant the required certificate permissions (e.g., 'Certificates Get', 'Certificates Import', 'Certificates Create') to the interacting identity in the Azure Key Vault's access policies or via Azure Role-Based Access Control (RBAC). -
ModuleNotFoundError: No module named 'azure.keyvault.certificates'
cause The 'azure-keyvault-certificates' package has not been installed or is not accessible within the current Python environment.fixInstall the library using pip: `pip install azure-keyvault-certificates azure-identity`. -
Azure.RequestFailedException: No certificate with private key found in the specified X.509 certificate content. Please specify X.509 certificate content with only one certificate containing private key. Status: 400 (Bad Request) ErrorCode: BadParameter
cause The certificate file being imported (e.g., PFX or PEM) does not contain its corresponding private key, or it includes multiple certificates when Key Vault expects a single certificate with a private key.fixEnsure the certificate file is in PFX or PEM format and explicitly bundles the private key. For PEM files, concatenate the certificate and its private key in the correct order within the same file. -
The specified PEM X.509 certificate content is in an unexpected format. Please check if certificate is in valid PEM format.
cause The PEM certificate file contains formatting issues such as incorrect line endings (e.g., Windows-style CRLF instead of Unix-style LF), missing 'BEGIN'/'END' markers, or the private key is in an unsupported format (e.g., PKCS#1 instead of PKCS#8).fixVerify that the PEM file uses Unix-style line endings (`\n`), contains the correct `-----BEGIN CERTIFICATE-----`/`-----END CERTIFICATE-----` and `-----BEGIN PRIVATE KEY-----`/`-----END PRIVATE KEY-----` markers, and convert PKCS#1 private keys to PKCS#8 format using `openssl pkcs8 -topk8 ...` if necessary.
Warnings
- breaking Azure RBAC (Role-Based Access Control) is now the default access control model for newly created Key Vaults with API version 2026-02-01 and later, replacing or complementing traditional access policies. Existing vaults retain their current model unless updated. Mixing RBAC and access policies can lead to unexpected permission behaviors.
- gotcha Common 'Access Denied' (403 Forbidden) errors often stem from insufficient permissions. A Key Vault certificate is composed of three interconnected objects: the certificate itself, an underlying key, and a secret. Access policies/RBAC roles must grant appropriate permissions to all three components (e.g., `certificates/get`, `keys/get`, `secrets/get`) for full functionality.
- gotcha Applications may fail unexpectedly due to expired certificates. While Key Vault supports auto-rotation, it needs proper configuration and monitoring.
- gotcha Frequent requests to Key Vault (e.g., retrieving certificates on every API call) can lead to service throttling (HTTP 429 Too Many Requests) due to rate limits. Key Vault is not designed as a runtime database.
- gotcha Importing certificates (PFX/PKCS#12 or PEM formats) can fail due to incorrect file format, missing private keys, or content type mismatches. PEM files must contain both the certificate and the private key.
- gotcha If certificate auto-rotation is enabled or a certificate's policy is updated, Key Vault will automatically generate new versions of certificates, potentially deprecating older ones. Services that pin to specific certificate fingerprints (e.g., for security reasons) will break when a new version is issued.
- breaking The `create_self_signed` method on the `CertificatePolicy` class is not a direct static method in certain versions of the Azure Key Vault Certificates client library for Python. Attempting to call it directly will result in an `AttributeError`.
- breaking The `CertificatePolicy.create_self_signed` method has been removed or deprecated in recent versions of the Azure Key Vault Certificates library. Attempting to use this method will result in an AttributeError.
Install
-
pip install azure-keyvault-certificates azure-identity
Imports
- CertificateClient
from azure.keyvault.certificates import CertificateClient
- CertificatePolicy
from azure.keyvault.certificates import CertificatePolicy
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.keyvault.certificates import CertificateClient, CertificatePolicy
from azure.identity import DefaultAzureCredential
# Set your Key Vault name and certificate name as environment variables or replace directly.
# For local development, ensure you are logged in via Azure CLI (az login).
keyvault_name = os.environ.get('AZURE_KEYVAULT_NAME', 'YOUR_KEY_VAULT_NAME')
certificate_name = 'MySampleCertificate'
# Construct the Key Vault URL
vault_url = f"https://{keyvault_name}.vault.azure.net"
# Authenticate using DefaultAzureCredential
# This credential type is suitable for local development and managed identity in production.
credential = DefaultAzureCredential()
# Create a CertificateClient
certificate_client = CertificateClient(vault_url=vault_url, credential=credential)
async def manage_certificate():
print(f"Creating a self-signed certificate '{certificate_name}' in {keyvault_name}...")
# Create a certificate policy for a self-signed certificate
policy = CertificatePolicy.create_self_signed(
subject="CN=www.contoso.com",
issuer_name="Self",
validity_in_months=12
)
# Begin creating the certificate - this is a long-running operation
poller = await certificate_client.begin_create_certificate(certificate_name, policy)
# Wait for the certificate creation to complete
created_certificate = await poller.result()
print(f"Certificate '{created_certificate.name}' created with thumbprint: {created_certificate.properties.x509_thumbprint}")
print(f"Retrieving certificate '{certificate_name}'...")
retrieved_certificate = await certificate_client.get_certificate(certificate_name)
print(f"Retrieved certificate version: {retrieved_certificate.properties.version}")
print(f"Deleting certificate '{certificate_name}'...")
# Begin deleting the certificate - this is a long-running operation
delete_poller = await certificate_client.begin_delete_certificate(certificate_name)
await delete_poller.wait()
print(f"Certificate '{certificate_name}' deleted.")
# Don't forget to close the credential and client when done (especially for async)
await certificate_client.close()
await credential.close()
# Example of how to run the async function
import asyncio
if __name__ == '__main__':
# Make sure to set AZURE_KEYVAULT_NAME environment variable
# e.g., export AZURE_KEYVAULT_NAME="my-unique-vault-name"
# And login via Azure CLI: az login
asyncio.run(manage_certificate())