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
Prerequisites
-
Python 2.7, 3.5.3, or later to use this package.
-
A Key Vault. If you need to create a Key Vault, you can use the Azure Cloud Shell to create one with this Azure CLI command. Replace
<your-resource-group-name>
and<your-key-vault-name>
with your own unique names:az keyvault create --resource-group <your resource group name> --name <your key vault name>
Output:
{ "id": "...", "location": "westus2", "name": "<your key vault name>", "properties": { "accessPolicies": [...], "createMode": null, "enablePurgeProtection": null, "enableSoftDelete": null, "enabledForDeployment": false, "enabledForDiskEncryption": null, "enabledForTemplateDeployment": null, "networkAcls": null, "provisioningState": "Succeeded", "sku": { "name": "standard" }, "tenantId": "...", "vaultUri": "https://<your key vault name>.vault.azure.net/" }, "resourceGroup": "<your resource group name>", "type": "Microsoft.KeyVault/vaults" }
The
"vaultUri"
property is thevault_url
used byCertificateClient
.
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
Use this Azure Cloud Shell snippet to create a service principal:
-
Create a service principal and configure its access to Azure resources:
az ad sp create-for-rbac -n <your-application-name> --skip-assignment
Output:
{ "appId": "generated app id", "displayName": "your-application-name", "name": "http://your-application-name", "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 <your-key-vault-name> --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_url=<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.
Certificate
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:
Examples
This section contains code snippets covering common tasks:
- Create a Certificate
- Retrieve a Certificate
- Update an existing Certificate
- Delete a Certificate
- List Certificates
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")
create_certificate_poller.wait()
print(create_certificate_poller.result())
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")
print(certificate.name)
print(certificate.version)
print(certificate.policy.id)
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")
print(certificate.name)
print(certificate.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(name="cert-name", tags=tags)
print(updated_certificate.name)
print(updated_certificate.version)
print(updated_certificate.updated)
print(updated_certificate.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")
print(deleted_certificate.name)
print(deleted_certificate.deleted_date)
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
print(certificate.name)
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
print(create_certificate_result)
Asynchronously list certificates
This example lists all the certificates in the client's vault:
certificates = certificate_client.list_certificates()
async for certificate in certificates:
print(certificate.name)
Troubleshooting
General
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 HttpResponseError
try:
certificate_client.get_certificate(name="deleted_certificate", version="deleted_certificate_version")
except HttpResponseError as e:
print(e.message)
Output: "certificate not found:deleted_certificate"
Logging
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__)
logger.setLevel(logging.DEBUG)
# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
# Configure a file output
file_handler = logging.FileHandler(filename)
logger.addHandler(file_handler)
# Enable network trace logging. This will be logged at DEBUG level.
config = CertificateClient.create_config(credential=credential, logging_enable=True)
client = CertificateClient(vault_url=url, credential=credential, config=config)
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:
- test_examples_certificates.py and test_examples_certificates_async.py - code snippets from the library's documentation
- hello_world.py and hello_world_async.py - create/get/update/delete certificates
- backup_restore_operations.py and backup_restore_operations_async.py - backup and recover certificates
Additional Documentation
For more extensive documentation on Azure Key Vault, see the API reference documentation.
Contributing
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 https://cla.microsoft.com.
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 opencode@microsoft.com with any additional questions or comments.
Release History
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. For more information about preview releases of other Azure SDK libraries, please visit https://aka.ms/azure-sdk-preview1-python.
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- see this package's documentation , and the Azure Identity documentation for more information
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 inazure.keyvault.certificates
- Async clients use aiohttp for transport by default. See azure-core documentation for more information about using other transports.
- the
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for azure-keyvault-certificates-4.0.0b3.zip
Algorithm | Hash digest | |
---|---|---|
SHA256 | cceb84c7d2976a180cfdd82cce6da2fac0e7da892a391cc5aa90882979993824 |
|
MD5 | e51d153d2e9854ecb1e689f0521d2db2 |
|
BLAKE2b-256 | d494fdd24f930a030f3d9af801de5b64fed318465869435da7986d3a729117c6 |
Hashes for azure_keyvault_certificates-4.0.0b3-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8160706a6d1fd1cc1146ccafbe5d7d72b5c69d9ed6fc33564620c5320da5d626 |
|
MD5 | c2415f410ab9c508fe8864f145c401df |
|
BLAKE2b-256 | d11e793db0593d11fd594127ac2c43cab31173c1c588f476e4e8bf13cf59f151 |