Package: azure-keyvault-secrets
Azure Key Vault Secrets client library for PythonAzure Key Vault helps solve the following problems:Secrets management (this library) -
securely store and control access to tokens, passwords, certificates, API keys,
and other secretsCryptographic key management
(azure-keyvault-keys) -
create, store, and control access to the keys used to encrypt your dataCertificate management
(azure-keyvault-certificates) -
create, manage, and deploy public and private SSL/TLS certificatesVault administration (azure-keyvault-administration) - role-based access control (RBAC), and vault-level backup and restore optionsSource code|Package (PyPI)|Package (Conda)|API reference documentation|Product documentation|SamplesDisclaimerAzure 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.8 or later is required to use this package. For more details, please refer toAzure SDK for Python version support policy.Getting startedInstall packagesInstallazure-keyvault-secretsandazure-identitywithpip:pipinstallazure-keyvault-secretsazure-identityazure-identityis used for Azure Active Directory
authentication as demonstrated below.PrerequisitesAnAzure subscriptionPython 3.8 or laterAn existingAzure Key Vault. If you need to create one, you can do so using the Azure CLI by following the steps inthis document.Authenticate the clientIn order to interact with the Azure Key Vault service, you will need an instance of aSecretClient, as well as avault urland a credential object. This document demonstrates using aDefaultAzureCredential, which is appropriate for most scenarios, including local development and production environments. We recommend using amanaged identityfor authentication in production environments.Seeazure-identitydocumentation for more information about other methods of authentication and their corresponding credential types.Create a clientAfter configuring your environment for theDefaultAzureCredentialto use a suitable method of authentication, you can do the following to create a secret client (replacing the value ofVAULT_URLwith 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, importazure.keyvault.secrets.aio'sSecretClientinstead.Key conceptsSecretA 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 theKey Vault documentation.SecretClientcan set secret values in the vault, update
secret metadata, and delete secrets, as shown in theexamplesbelow.ExamplesThis section contains code snippets covering common tasks:Set a secretRetrieve a secretUpdate secret metadataDelete a secretList secretsAsync APIAsynchronously create a secretAsynchronously list secretsSet a secretset_secretcreates new secrets and changes the values of existing secrets. If no secret with the
given name exists,set_secretcreates a new secret with that name and the
given value. If the given name is in use,set_secretcreates a new version
of that secret, with the given value.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientcredential=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 secretget_secretretrieves a secret previously stored in the Key Vault.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientcredential=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 metadataupdate_secret_propertiesupdates a secret's metadata. It cannot change the secret's value; useset_secretto set a secret's
value.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientcredential=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)Delete a secretbegin_delete_secretrequests Key Vault delete a secret, returning a poller which allows you to wait for the deletion to finish. Waiting is
helpful when the vault hassoft-deleteenabled, and you want to purge (permanently delete) the secret as
soon as possible. Whensoft-deleteis disabled,begin_delete_secretitself is permanent.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientcredential=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 secretslist_properties_of_secretslists the properties of all of the secrets in the client's vault. This list doesn't include the secret's values.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientcredential=DefaultAzureCredential()secret_client=SecretClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)secret_properties=secret_client.list_properties_of_secrets()forsecret_propertyinsecret_properties:# the list doesn't include values or versions of the secretsprint(secret_property.name)Async APIThis library includes a complete set of async APIs. To use them, you must
first install an async transport, such asaiohttp.
Seeazure-core documentationfor more information.Async clients and credentials should be closed when they're no longer needed. These
objects are async context managers and define asyncclosemethods. For
example:fromazure.identity.aioimportDefaultAzureCredentialfromazure.keyvault.secrets.aioimportSecretClientcredential=DefaultAzureCredential()# call close when the client and credential are no longer neededclient=SecretClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)...awaitclient.close()awaitcredential.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)asyncwithclient:asyncwithcredential:...Asynchronously create a secretset_secretcreates a secret in the Key Vault with the specified optional arguments.fromazure.identity.aioimportDefaultAzureCredentialfromazure.keyvault.secrets.aioimportSecretClientcredential=DefaultAzureCredential()secret_client=SecretClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)secret=awaitsecret_client.set_secret("secret-name","secret-value")print(secret.name)print(secret.value)print(secret.properties.version)Asynchronously list secretslist_properties_of_secretslists the properties of all of the secrets in the client's vault.fromazure.identity.aioimportDefaultAzureCredentialfromazure.keyvault.secrets.aioimportSecretClientcredential=DefaultAzureCredential()secret_client=SecretClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)secret_properties=secret_client.list_properties_of_secrets()asyncforsecret_propertyinsecret_properties:# the list doesn't include values or versions of the secretsprint(secret_property.name)TroubleshootingSee theazure-keyvault-secretstroubleshooting guidefor details on how to diagnose various failure scenarios.GeneralKey Vault clients raise exceptions defined inazure-core.
For example, if you try to get a key that doesn't exist in the vault,SecretClientraisesResourceNotFoundError:fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientfromazure.core.exceptionsimportResourceNotFoundErrorcredential=DefaultAzureCredential()secret_client=SecretClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)try:secret_client.get_secret("which-does-not-exist")exceptResourceNotFoundErrorase:print(e.message)LoggingThis library uses the standardlogginglibrary 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 thelogging_enableargument:fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.secretsimportSecretClientimportsysimportlogging# 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_enablecan 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 stepsSeveral samples are available in the Azure SDK for Python GitHub repository.
These provide example code for additional Key Vault scenarios:Create/get/update/delete secrets(async version)Basic list operations for secrets(async version)Back up and restore secrets(async version)Recover and purge secrets(async version)Additional DocumentationFor more extensive documentation on Azure Key Vault, see theAPI reference documentation.ContributingThis 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, visithttps://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 theMicrosoft Open Source Code of Conduct.
For more information, see theCode of Conduct FAQor
contactopencode@microsoft.comwith any additional questions or comments.Release History4.8.0 (2024-02-22)Features AddedAdded support for service API version7.5Bugs Fixed(From 4.8.0b1) Token requests made during AD FS authentication no longer specify an erroneous "adfs" tenant ID
(#29888)Other ChangesPython 3.7 is no longer supported. Please use Python version 3.8 or later.asynciois no longer directly referenced by the library
(#33819)Updated minimumazure-coreversion to 1.29.5Droppedazure-commonrequirement4.8.0b2 (2023-11-03)Features AddedAdded support for service API version7.5-preview.1Other ChangesKey Vault API version7.5-preview.1is now the default4.8.0b1 (2023-05-16)Bugs FixedToken requests made during AD FS authentication no longer specify an erroneous "adfs" tenant ID
(#29888)4.7.0 (2023-03-16)Features AddedAdded support for service API version7.4Clients each have asend_requestmethod that can be used to send custom requests using the
client's existing pipeline (#25172)Other ChangesPython 3.6 is no longer supported. Please use Python version 3.7 or later.Key Vault API version7.4is now the defaultUpdated minimumazure-coreversion to 1.24.0DroppedmsrestrequirementAdded requirement forisodate>=0.6.1(isodatewas required bymsrest)Added requirement fortyping-extensions>=4.0.14.6.0 (2022-09-19)Breaking ChangesClients verify the challenge resource matches the vault domain. This should affect few customers,
who can provideverify_challenge_resource=Falseto client constructors to disable.
Seehttps://aka.ms/azsdk/blog/vault-urifor more information.4.5.1 (2022-08-11)Other ChangesDocumentation improvements
(#25039)4.5.0b1 (2022-06-07)Bugs FixedPort numbers are now preserved in thevault_urlproperty of aKeyVaultSecretIdentifier(#24446)4.4.0 (2022-03-28)Features AddedKey Vault API version 7.3 is now the defaultAdded support for multi-tenant authentication when usingazure-identity1.8.0 or newer (#20698)(From 4.4.0b3) Addedmanagedproperty to SecretPropertiesOther Changes(From 4.4.0b3) Python 2.7 is no longer supported. Please use Python version 3.6 or later.Updated minimumazure-coreversion to 1.20.0(From 4.4.0b2) To support multi-tenant authentication,get_tokencalls during challenge
authentication requests now pass in atenant_idkeyword argument
(#20698). Seehttps://aka.ms/azsdk/python/identity/tokencredentialfor more details on how to integrate
this parameter ifget_tokenis implemented by a custom credential.4.4.0b3 (2022-02-08)Features AddedAddedmanagedproperty to SecretPropertiesOther ChangesPython 2.7 is no longer supported. Please use Python version 3.6 or later.(From 4.4.0b2) To support multi-tenant authentication,get_tokencalls during challenge
authentication requests now pass in atenant_idkeyword argument
(#20698)4.4.0b2 (2021-11-11)Features AddedAdded support for multi-tenant authentication when usingazure-identity1.7.1 or newer
(#20698)Other ChangesUpdated minimumazure-coreversion to 1.15.04.4.0b1 (2021-09-09)Features AddedKey Vault API version 7.3-preview is now the defaultOther ChangesUpdated type hints to fix mypy errors
(#19158)4.3.0 (2021-06-22)This is the last version to support Python 3.5. The next version will require Python 2.7 or 3.6+.FixedCorrect typing for async paging methodsChangedKey Vault API version 7.2 is now the defaultUpdated minimummsrestversion to 0.6.21AddedAdded classKeyVaultSecretIdentifierthat parses out a full ID returned by Key Vault,
so users can easily access the secret'sname,vault_url, andversion.4.2.0 (2020-08-11)FixedValues ofx-ms-keyvault-regionandx-ms-keyvault-service-versionheaders
are no longer redacted in logging outputChangedKey Vault API version 7.1 is now the defaultUpdated minimumazure-coreversion to 1.7.0AddedAt construction, clients accept aCustomHookPolicythrough the optional
keyword argumentcustom_hook_policyAll client requests include a unique ID in the headerx-ms-client-request-idDependency onazure-commonfor multiapi support4.2.0b1 (2020-03-10)Support for Key Vault API version 7.1-preview
(#10124)Addedrecoverable_daystoCertificatePropertiesAddedApiVersionenum identifying Key Vault versions supported by this package4.1.0 (2020-03-10)SecretClientinstances have aclosemethod which closes opened sockets.
Used as a context manager, aSecretClientcloses opened sockets on exit.
(#9906)Pollers no longer sleep after operation completion
(#9991)4.0.1 (2020-02-11)azure.keyvault.secretsdefines__version__Challenge authentication policy preserves request options
(#8999)Updatedmsrestrequirement to >=0.6.0Challenge authentication policy requires TLS
(#9457)Methods no longer raise the internal errorKeyVaultErrorException(#9690)4.0.0 (2019-10-31)Breaking changes:Moved optional parameters of two methods into kwargs (docsdetail the new keyword arguments):set_secretnow has positional parametersnameandvalueupdate_secret_propertiesnow has positional parametersnameand
(optional)versionRenamedlist_secretstolist_properties_of_secretsRenamedlist_secret_versionstolist_properties_of_secret_versionsRenamed sync methoddelete_secrettobegin_delete_secretThe sync methodbegin_delete_secretand asyncdelete_secretnow return pollers that return aDeletedSecretRenamedSecrettoKeyVaultSecretKeyVaultSecretpropertiescreated,expires, andupdatedrenamed tocreated_on,expires_on, andupdated_onThevault_endpointparameter ofSecretClienthas been renamed tovault_urlThe propertyvault_endpointhas been renamed tovault_urlin all models4.0.0b4 (2019-10-08)Breaking changes:Secretnow has attributeproperties, which holds certain properties of the
secret, such asversion. This changes the shape of the returnedSecrettype,
as certain properties ofSecret(such asversion) have to be accessed
through thepropertiesproperty.update_secrethas been renamed toupdate_secret_propertiesThevault_urlparameter ofSecretClienthas been renamed tovault_endpointThe propertyvault_urlhas been renamed tovault_endpointin all modelsFixes and improvementslist_secretsandlist_secret_versionsreturn the correct type4.0.0b3 (2019-09-11)This release includes only internal changes.4.0.0b2 (2019-08-06)Breaking changes:Removedazure.core.Configurationfrom the public API in preparation for a
revamped configuration API. Staticcreate_configmethods have been renamed_create_config, and will be removed in a future release.This version of the library requiresazure-core1.0.0b2If you later want to revert to a version requiring azure-core 1.0.0b1,
of this or another Azure SDK library, you must explicitly install azure-core
1.0.0b1 as well. For example:pip install azure-core==1.0.0b1 azure-keyvault-secrets==4.0.0b1New features:Distributed tracing framework OpenCensus is now supportedAdded support for HTTP challenge based authentication, allowing clients to
interact with vaults in sovereign clouds.4.0.0b1 (2019-06-28)Version 4.0.0b1 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 visithttps://aka.ms/azure-sdk-preview1-python.This library is not a direct replacement forazure-keyvault. Applications
using that library would require code changes to useazure-keyvault-secrets.
This package'sdocumentationandsamplesdemonstrate the new API.Major changes fromazure-keyvaultPackages scoped by functionalityazure-keyvault-secretscontains a client for secret operations,azure-keyvault-keyscontains a client for key operationsClient instances are scoped to vaults (an instance interacts with one vault
only)Asynchronous API supported on Python 3.5.3+theazure.keyvault.secrets.aionamespace contains an async equivalent of
the synchronous client inazure.keyvault.secretsAuthentication usingazure-identitycredentialssee this package'sdocumentation, and theAzure Identity documentationfor more informationazure-keyvaultfeatures not implemented in this libraryCertificate management APIsNational cloud support. This release supports public global cloud vaults,
e.g. https://{vault-name}.vault.azure.net