Azure Key Vault Secrets client library for Python¶
Azure Key Vault helps solve the following problems:
Secrets management (this library) - securely store and control access to tokens, passwords, certificates, API keys, and other secrets
Cryptographic key management (azure-keyvault-keys) - create, store, and control access to the keys used to encrypt your data
Certificate management (azure-keyvault-certificates) - create, manage, and deploy public and private SSL/TLS certificates
Vault administration (azure-keyvault-administration) - role-based access control (RBAC), and vault-level backup and restore options
Source code | Package (PyPI) | Package (Conda) | API reference documentation | Product documentation | Samples
Disclaimer¶
Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691. Python 3.8 or later is required to use this package. For more details, please refer to Azure SDK for Python version support policy.
Getting started¶
Install packages¶
Install azure-keyvault-secrets and azure-identity with pip:
pip install azure-keyvault-secrets azure-identity
azure-identity is used for Azure Active Directory authentication as demonstrated below.
Prerequisites¶
Python 3.8 or later
An existing Azure Key Vault. If you need to create one, you can do so using the Azure CLI by following the steps in this document.
Authenticate the client¶
In order to interact with the Azure Key Vault service, you will need an instance of a SecretClient, as well as a vault url and a credential object. This document demonstrates using a DefaultAzureCredential, which is appropriate for most scenarios, including local development and production environments. We recommend using a managed identity for authentication in production environments.
See azure-identity documentation for more information about other methods of authentication and their corresponding credential types.
Create a client¶
After configuring your environment for the DefaultAzureCredential to use a suitable method of authentication, you can do the following to create a secret client (replacing the value of VAULT_URL
with your vault’s URL):
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = SecretClient(vault_url=VAULT_URL, credential=credential)
NOTE: For an asynchronous client, import
azure.keyvault.secrets.aio
’sSecretClient
instead.
Key concepts¶
Secret¶
A secret consists of a secret value and its associated metadata and management information. This library handles secret values as strings, but Azure Key Vault doesn’t store them as such. For more information about secrets and how Key Vault stores and manages them, see the Key Vault documentation.
SecretClient can set secret values in the vault, update secret metadata, and delete secrets, as shown in the examples below.
Examples¶
This section contains code snippets covering common tasks:
Set a secret¶
set_secret
creates new secrets and changes the values of existing secrets. If no secret with the
given name exists, set_secret
creates a new secret with that name and the
given value. If the given name is in use, set_secret
creates a new version
of that secret, with the given value.
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
secret = secret_client.set_secret("secret-name", "secret-value")
print(secret.name)
print(secret.value)
print(secret.properties.version)
Retrieve a secret¶
get_secret retrieves a secret previously stored in the Key Vault.
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
secret = secret_client.get_secret("secret-name")
print(secret.name)
print(secret.value)
Update secret metadata¶
update_secret_properties updates a secret’s metadata. It cannot change the secret’s value; use set_secret to set a secret’s value.
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
# Clients may specify the content type of a secret to assist in interpreting the secret data when it's retrieved
content_type = "text/plain"
# We will also disable the secret for further use
updated_secret_properties = secret_client.update_secret_properties("secret-name", content_type=content_type, enabled=False)
print(updated_secret_properties.updated_on)
print(updated_secret_properties.content_type)
print(updated_secret_properties.enabled)
Delete a secret¶
begin_delete_secret
requests Key Vault delete a secret, returning a poller which allows you to wait for the deletion to finish. Waiting is
helpful when the vault has soft-delete enabled, and you want to purge (permanently delete) the secret as
soon as possible. When soft-delete is disabled, begin_delete_secret
itself is permanent.
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
deleted_secret = secret_client.begin_delete_secret("secret-name").result()
print(deleted_secret.name)
print(deleted_secret.deleted_date)
List secrets¶
list_properties_of_secrets lists the properties of all of the secrets in the client’s vault. This list doesn’t include the secret’s values.
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
secret_properties = secret_client.list_properties_of_secrets()
for secret_property in secret_properties:
# the list doesn't include values or versions of the secrets
print(secret_property.name)
Async API¶
This library includes a complete set of async APIs. To use them, you must first install an async transport, such as aiohttp. See azure-core documentation for more information.
Async clients and credentials should be closed when they’re no longer needed. These
objects are async context managers and define async close
methods. For
example:
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.secrets.aio import SecretClient
credential = DefaultAzureCredential()
# call close when the client and credential are no longer needed
client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
...
await client.close()
await credential.close()
# alternatively, use them as async context managers (contextlib.AsyncExitStack can help)
client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
async with client:
async with credential:
...
Asynchronously create a secret¶
set_secret creates a secret in the Key Vault with the specified optional arguments.
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.secrets.aio import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
secret = await secret_client.set_secret("secret-name", "secret-value")
print(secret.name)
print(secret.value)
print(secret.properties.version)
Asynchronously list secrets¶
list_properties_of_secrets lists the properties of all of the secrets in the client’s vault.
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.secrets.aio import SecretClient
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
secret_properties = secret_client.list_properties_of_secrets()
async for secret_property in secret_properties:
# the list doesn't include values or versions of the secrets
print(secret_property.name)
Troubleshooting¶
See the azure-keyvault-secrets
troubleshooting guide
for details on how to diagnose various failure scenarios.
General¶
Key Vault clients raise exceptions defined in azure-core. For example, if you try to get a key that doesn’t exist in the vault, SecretClient raises ResourceNotFoundError:
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from azure.core.exceptions import ResourceNotFoundError
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
try:
secret_client.get_secret("which-does-not-exist")
except ResourceNotFoundError as e:
print(e.message)
Logging¶
This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.
Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with the logging_enable
argument:
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
import sys
import logging
# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)
# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
credential = DefaultAzureCredential()
# This client will log detailed information about its HTTP sessions, at DEBUG level
secret_client = SecretClient(
vault_url="https://my-key-vault.vault.azure.net/",
credential=credential,
logging_enable=True
)
Similarly, logging_enable
can enable detailed logging for a single operation,
even when it isn’t enabled for the client:
secret_client.get_secret("my-secret", logging_enable=True)
Next steps¶
Several samples are available in the Azure SDK for Python GitHub repository. These provide example code for additional Key Vault scenarios:
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.
Indices and tables¶
- azure.keyvault.secrets package
ApiVersion
ApiVersion.capitalize()
ApiVersion.casefold()
ApiVersion.center()
ApiVersion.count()
ApiVersion.encode()
ApiVersion.endswith()
ApiVersion.expandtabs()
ApiVersion.find()
ApiVersion.format()
ApiVersion.format_map()
ApiVersion.index()
ApiVersion.isalnum()
ApiVersion.isalpha()
ApiVersion.isascii()
ApiVersion.isdecimal()
ApiVersion.isdigit()
ApiVersion.isidentifier()
ApiVersion.islower()
ApiVersion.isnumeric()
ApiVersion.isprintable()
ApiVersion.isspace()
ApiVersion.istitle()
ApiVersion.isupper()
ApiVersion.join()
ApiVersion.ljust()
ApiVersion.lower()
ApiVersion.lstrip()
ApiVersion.maketrans()
ApiVersion.partition()
ApiVersion.removeprefix()
ApiVersion.removesuffix()
ApiVersion.replace()
ApiVersion.rfind()
ApiVersion.rindex()
ApiVersion.rjust()
ApiVersion.rpartition()
ApiVersion.rsplit()
ApiVersion.rstrip()
ApiVersion.split()
ApiVersion.splitlines()
ApiVersion.startswith()
ApiVersion.strip()
ApiVersion.swapcase()
ApiVersion.title()
ApiVersion.translate()
ApiVersion.upper()
ApiVersion.zfill()
ApiVersion.V2016_10_01
ApiVersion.V7_0
ApiVersion.V7_1
ApiVersion.V7_2
ApiVersion.V7_3
ApiVersion.V7_4
ApiVersion.V7_5
DeletedSecret
KeyVaultSecret
KeyVaultSecretIdentifier
SecretClient
SecretClient.backup_secret()
SecretClient.begin_delete_secret()
SecretClient.begin_recover_deleted_secret()
SecretClient.close()
SecretClient.get_deleted_secret()
SecretClient.get_secret()
SecretClient.list_deleted_secrets()
SecretClient.list_properties_of_secret_versions()
SecretClient.list_properties_of_secrets()
SecretClient.purge_deleted_secret()
SecretClient.restore_secret_backup()
SecretClient.send_request()
SecretClient.set_secret()
SecretClient.update_secret_properties()
SecretClient.vault_url
SecretProperties
SecretProperties.content_type
SecretProperties.created_on
SecretProperties.enabled
SecretProperties.expires_on
SecretProperties.id
SecretProperties.key_id
SecretProperties.managed
SecretProperties.name
SecretProperties.not_before
SecretProperties.recoverable_days
SecretProperties.recovery_level
SecretProperties.tags
SecretProperties.updated_on
SecretProperties.vault_url
SecretProperties.version
- Subpackages
- azure.keyvault.secrets.aio package
SecretClient
SecretClient.backup_secret()
SecretClient.close()
SecretClient.delete_secret()
SecretClient.get_deleted_secret()
SecretClient.get_secret()
SecretClient.list_deleted_secrets()
SecretClient.list_properties_of_secret_versions()
SecretClient.list_properties_of_secrets()
SecretClient.purge_deleted_secret()
SecretClient.recover_deleted_secret()
SecretClient.restore_secret_backup()
SecretClient.send_request()
SecretClient.set_secret()
SecretClient.update_secret_properties()
SecretClient.vault_url
- azure.keyvault.secrets.aio package