This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Azure Key Vault helps solve the following problems:
Source code|Package (PyPI)|Package (Conda)|API reference documentation|Product documentation|Samples
Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer tohttps://github.com/Azure/azure-sdk-for-python/issues/20691.Python 3.9 or later is required to use this package. For more details, please refer toAzure SDK for Python version support policy.
Installazure-keyvault-secrets andazure-identity withpip:
pip install azure-keyvault-secrets azure-identity
azure-identity is used for Azure Active Directoryauthentication as demonstrated below.
In order to interact with the Azure Key Vault service, you will need an instance of aSecretClient, as well as avault url and a credential object. This document demonstrates using aDefaultAzureCredential, which is appropriate for most scenarios, including local development and production environments. We recommend using amanaged identity for authentication in production environments.
Seeazure-identity documentation for more information about other methods of authentication and their corresponding credential types.
After configuring your environment for theDefaultAzureCredential to use a suitable method of authentication, you can do the following to create a secret client (replacing the value ofVAULT_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.
A secret consists of a secret value and its associated metadata and managementinformation. This library handles secret values as strings, but Azure Key Vaultdoesn't store them as such. For more information about secrets and how KeyVault stores and manages them, see theKey Vault documentation.
SecretClient can set secret values in the vault, updatesecret metadata, and delete secrets, as shown in theexamples below.
This section contains code snippets covering common tasks:
set_secretcreates new secrets and changes the values of existing secrets. If no secret with thegiven name exists,set_secret
creates a new secret with that name and thegiven value. If the given name is in use,set_secret
creates a new versionof that secret, with the given value.
from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientcredential = 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)
get_secretretrieves a secret previously stored in the Key Vault.
from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientcredential = 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_propertiesupdates a secret's metadata. It cannot change the secret's value; useset_secret to set a secret'svalue.
from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientcredential = 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 retrievedcontent_type = "text/plain"# We will also disable the secret for further useupdated_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)
begin_delete_secretrequests Key Vault delete a secret, returning a poller which allows you to wait for the deletion to finish. Waiting ishelpful when the vault hassoft-delete enabled, and you want to purge (permanently delete) the secret assoon as possible. Whensoft-delete is disabled,begin_delete_secret
itself is permanent.
from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientcredential = 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_properties_of_secretslists 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 DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientcredential = 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)
This library includes a complete set of async APIs. To use them, you mustfirst install an async transport, such asaiohttp.Seeazure-core documentationfor more information.
Async clients and credentials should be closed when they're no longer needed. Theseobjects are async context managers and define asyncclose
methods. Forexample:
from azure.identity.aio import DefaultAzureCredentialfrom azure.keyvault.secrets.aio import SecretClientcredential = DefaultAzureCredential()# call close when the client and credential are no longer neededclient = 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: ...
set_secretcreates a secret in the Key Vault with the specified optional arguments.
from azure.identity.aio import DefaultAzureCredentialfrom azure.keyvault.secrets.aio import SecretClientcredential = 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)
list_properties_of_secretslists the properties of all of the secrets in the client's vault.
from azure.identity.aio import DefaultAzureCredentialfrom azure.keyvault.secrets.aio import SecretClientcredential = 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)
See theazure-keyvault-secrets
troubleshooting guidefor details on how to diagnose various failure scenarios.
Key Vault clients raise exceptions defined inazure-core.For example, if you try to get a key that doesn't exist in the vault,SecretClient raisesResourceNotFoundError:
from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientfrom azure.core.exceptions import ResourceNotFoundErrorcredential = 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)
This library uses the standardlogging library for logging.Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFOlevel.
Detailed DEBUG level logging, including request/response bodies and unredactedheaders, can be enabled on a client with thelogging_enable
argument:
from azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClientimport sysimport logging# Create a logger for the 'azure' SDKlogger = logging.getLogger('azure')logger.setLevel(logging.DEBUG)# Configure a console outputhandler = logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)credential = DefaultAzureCredential()# This client will log detailed information about its HTTP sessions, at DEBUG levelsecret_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)
Several samples are available in the Azure SDK for Python GitHub repository.These provide example code for additional Key Vault scenarios:
For more extensive documentation on Azure Key Vault, see theAPI reference documentation.
This project welcomes contributions and suggestions. Most contributions requireyou to agree to a Contributor License Agreement (CLA) declaring that you havethe right to, and actually do, grant us the rights to use your contribution.For details, visithttps://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whetheryou need to provide a CLA and decorate the PR appropriately (e.g., label,comment). Simply follow the instructions provided by the bot. You will onlyneed to do this once across all repos using our CLA.
This project has adopted theMicrosoft Open Source Code of Conduct.For more information, see theCode of Conduct FAQ orcontact opencode@microsoft.com with any additional questions or comments.
Was this page helpful?
Was this page helpful?