Skip to main content

Microsoft Azure Key Vault Certificates Client Library for Python

Project description

Azure Key Vault Certificates client library for Python

Azure Key Vault helps solve the following problems:

  • Certificate management (this library) - create, manage, and deploy public and private SSL/TLS certificates
  • Cryptographic key management (azure-keyvault-keys) - create, store, and control access to the keys used to encrypt your data
  • Secrets management (azure-keyvault-secrets) - securely store and control access to tokens, passwords, certificates, API keys, and other secrets

Source code | Package (PyPI) | API reference documentation | Product documentation | Samples

Getting started

Install the package

Install the Azure Key Vault client library for Python with pip:

pip install azure-keyvault-certificates


  • An Azure subscription
  • Python 2.7, 3.5.3, or later
  • A Key Vault. If you need to create one, you can use the Azure Cloud Shell to create one with these commands (replace "my-resource-group" and "my-key-vault" with your own, unique names):
    • (Optional) if you want a new resource group to hold the Key Vault:

      az group create --name my-resource-group --location westus2
    • Create the Key Vault:

      az keyvault create --resource-group my-resource-group --name my-key-vault


          "id": "...",
          "location": "westus2",
          "name": "my-key-vault",
          "properties": {
              "accessPolicies": [...],
              "createMode": null,
              "enablePurgeProtection": null,
              "enableSoftDelete": null,
              "enabledForDeployment": false,
              "enabledForDiskEncryption": null,
              "enabledForTemplateDeployment": null,
              "networkAcls": null,
              "provisioningState": "Succeeded",
              "sku": { "name": "standard" },
              "tenantId": "...",
              "vaultUri": ""
          "resourceGroup": "my-resource-group",
          "type": "Microsoft.KeyVault/vaults"

      The "vaultUri" property is the vault_endpoint used by CertificateClient

Authenticate the client

In order to interact with a Key Vault's certificates, you'll need an instance of the CertificateClient class. Creating one requires a vault url and credential. This document demonstrates using DefaultAzureCredential as the credential, authenticating with a service principal's client id, secret, and tenant id. Other authentication methods are supported. See the azure-identity documentation for more details.

Create a service principal

This Azure Cloud Shell snippet shows how to create a new service principal. Before using it, replace "your-application-name" with a more appropriate name for your service principal.

  • Create a service principal:

    az ad sp create-for-rbac --name http://my-application --skip-assignment


        "appId": "generated app id",
        "displayName": "my-application",
        "name": "http://my-application",
        "password": "random password",
        "tenant": "tenant id"
    • Use the output to set AZURE_CLIENT_ID (appId), AZURE_CLIENT_SECRET (password) and AZURE_TENANT_ID (tenant) environment variables. The following example shows a way to do this in Bash:
 export AZURE_CLIENT_ID="generated app id"
 export AZURE_CLIENT_SECRET="random password"
 export AZURE_TENANT_ID="tenant id"
  • Authorize the service principal to perform certificate operations in your Key Vault:
    az keyvault set-policy --name my-key-vault --spn $AZURE_CLIENT_ID --certificate-permissions backup create delete get import list purge recover restore update

    Possible certificate permissions: backup, create, delete, deleteissuers, get, getissuers, import, list, listissuers, managecontacts, manageissuers, purge, recover, restore, setissuers, update

Create a client

After setting the AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID environment variables, you can create the CertificateClient:

from azure.identity import DefaultAzureCredential
from azure.keyvault.certificates import CertificateClient

credential = DefaultAzureCredential()

# Create a new certificate client using the default credential
certificate_client = CertificateClient(vault_endpoint=<your-vault-url>, credential=credential)

Key concepts

With a CertificateClient you can get certificates from the vault, create new certificates and new versions of existing certificates, update certificate metadata, and delete certificates. You can also manage certificate issuers, contacts, and management policies of certificates. This is illustrated in the examples below.


A certificate is the fundamental resource within Azure KeyVault. From a developer's perspective, Key Vault APIs accept and return certificates as the Certificate type. In addition to the certificate data, the following attributes may be specified:

  • expires: Identifies the expiration time on or after which the certificate data should not be retrieved.
  • not_before: Identifies the time after which the certificate will be active.
  • enabled: Specifies whether the certificate data can be retrieved.
  • created: Indicates when this version of the certificate was created.
  • updated: Indicates when this version of the certificate was updated.

Certificate Client:


This section contains code snippets covering common tasks:

Create a Certificate

create_certificate creates a Certificate to be stored in the Azure Key Vault. If a certificate with the same name already exists, then a new version of the certificate is created. Before creating a certificate, a management policy for the certificate can be created or our default policy will be used. The create_certificate operation returns a long running operation poller.

create_certificate_poller = certificate_client.create_certificate(name="cert-name")


Retrieve a Certificate

get_certificate_with_policy retrieves a certificate previously stored in the Key Vault without having to specify version.

certificate = certificate_client.get_certificate_with_policy(name="cert-name")


get_certificate retrieves a certificate based on the certificate name and the version of the certificate. Version is required.

certificate = certificate_client.get_certificate(name="cert-name", version="cert-version")


Update an existing Certificate

update_certificate updates a certificate previously stored in the Key Vault.

# You can specify additional application-specific metadata in the form of tags.
tags = {"foo": "updated tag"}

updated_certificate= certificate_client.update_certificate_properties(name="cert-name", tags=tags)


Delete a Certificate

delete_certificate deletes a certificate previously stored in the Key Vault. When soft-delete is not enabled for the Key Vault, this operation permanently deletes the certificate.

deleted_certificate = certificate_client.delete_certificate(name="cert-name")


List Certificates

This example lists all the certificates in the specified Key Vault.

certificates = certificate_client.list_certificates()

for certificate in certificates:
    # this list doesn't include versions of the certificates

Async operations

This library includes a complete async API supported on Python 3.5+. To use it, you must first install an async transport, such as aiohttp. See azure-core documentation for more information.

Asynchronously create a Certificate

create_certificate creates a Certificate to be stored in the Azure Key Vault. If a certificate with the same name already exists, then a new version of the certificate is created. Before creating a certificate, a management policy for the certificate can be created or our default policy will be used. The create_certificate operation returns an async long running operation poller.

create_certificate_poller = await certificate_client.create_certificate(name="cert-name")

create_certificate_result = await create_certificate_poller

Asynchronously list certificates

This example lists all the certificates in the client's vault:

certificates = certificate_client.list_certificates()

async for certificate in certificates:



Key Vault clients raise exceptions defined in azure-core.

For example, if you try to retrieve a certificate after it is deleted a 404 error is returned, indicating resource not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.

from azure.core.exceptions import ResourceNotFoundError
    certificate_client.get_certificate(name="deleted_certificate", version="deleted_certificate_version")
except ResourceNotFoundError as e:

Output: "certificate not found:deleted_certificate"


Network trace logging is disabled by default for this library. When enabled, HTTP requests will be logged at DEBUG level using the logging library. You can configure logging to print debugging information to stdout or write it to a file:

import sys
import logging

# Create a logger for the 'azure' SDK
logger = logging.getLogger(__name__)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)

# Configure a file output
file_handler = logging.FileHandler(filename)

# Enable network trace logging. Each HTTP request will be logged at DEBUG level.
client = CertificateClient(vault_endpoint=url, credential=credential, logging_enable=True))

Network trace logging can also be enabled for any single operation:

certificate = certificate_client.get_certificate_with_policy(name="cert-name", logging_enable=True)

Next steps

Several samples are available in the Azure SDK for Python GitHub repository. These samples provide example code for additional Key Vault scenarios:

Additional Documentation

For more extensive documentation on Azure Key Vault, see the API reference documentation.


This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact with any additional questions or comments.


Release History

4.0.0b4 (2019-10-08)

Breaking changes

  • Enums JsonWebKeyCurveName and JsonWebKeyType have been renamed to KeyCurveName and KeyType, respectively.
  • Both async and sync versions of create_certificate now return pollers that return the created Certificate if creation is successful, and a CertificateOperation if not.
  • Certificate now has attribute properties, which holds certain properties of the certificate, such as version. This changes the shape of the Certificate type, as certain properties of Certificate (such as version) have to be accessed through the properties property. See the updated docs for details.
  • update_certificate has been renamed to update_certificate_properties
  • The vault_url parameter of CertificateClient has been renamed to vault_endpoint
  • The property vault_url has been renamed to vault_endpoint in all models

4.0.0b3 (2019-09-11)

Version 4.0.0b3 is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Key Vault's certificates.

This library is not a direct replacement for azure-keyvault. Applications using that library would require code changes to use azure-keyvault-certificates. This package's documentation and samples demonstrate the new API.

Breaking changes from azure-keyvault:

  • Packages scoped by functionality
    • azure-keyvault-certificates contains a client for certificate operations
  • Client instances are scoped to vaults (an instance interacts with one vault only)
  • Authentication using azure-identity credentials

New Features:

  • Distributed tracing framework OpenCensus is now supported
  • Asynchronous API supported on Python 3.5.3+
    • the azure.keyvault.certificates.aio namespace contains an async equivalent of the synchronous client in azure.keyvault.certificates
    • Async clients use aiohttp for transport by default. See azure-core documentation for more information about using other transports.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution (655.8 kB view hashes)

Uploaded Source

Built Distribution

azure_keyvault_certificates-4.0.0b4-py2.py3-none-any.whl (167.9 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page