Package: azure-keyvault-certificates
Azure Key Vault Certificates client library for PythonAzure Key Vault helps solve the following problems:Certificate management (this library) - create, manage, and deploy public and private SSL/TLS certificatesCryptographic key management
(azure-keyvault-keys) - create, store, and control access to the keys used to encrypt your dataSecrets management
(azure-keyvault-secrets) -
securely store and control access to tokens, passwords, certificates, API keys,
and other secretsVault 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 the packageInstallazure-keyvault-certificatesandazure-identitywithpip:pipinstallazure-keyvault-certificatesazure-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 aCertificateClient, 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 certificate client (replacing the value ofVAULT_URLwith your vault's URL):VAULT_URL=os.environ["VAULT_URL"]credential=DefaultAzureCredential()client=CertificateClient(vault_url=VAULT_URL,credential=credential)NOTE:For an asynchronous client, importazure.keyvault.certificates.aio'sCertificateClientinstead.Key conceptsCertificateClientWith aCertificateClientyou 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 theexamplesbelow.ExamplesThis section contains code snippets covering common tasks:Create a certificateRetrieve a certificateUpdate properties of an existing certificateDelete a certificateList properties of certificatesAsync operationsAsynchronously create a certificateAsynchronously list properties of certificatesCreate a certificatebegin_create_certificatecreates a certificate to be stored in the Azure Key Vault. If a certificate with the same name already exists, 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. This method returns a long running operation poller.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClient,CertificatePolicycredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)create_certificate_poller=certificate_client.begin_create_certificate(certificate_name="cert-name",policy=CertificatePolicy.get_default())print(create_certificate_poller.result())If you would like to check the status of your certificate creation, you can callstatus()on the poller orget_certificate_operationwith the name of the certificate.Retrieve a certificateget_certificateretrieves the latest version of a certificate previously stored in the Key Vault.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClientcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)certificate=certificate_client.get_certificate("cert-name")print(certificate.name)print(certificate.properties.version)print(certificate.policy.issuer_name)get_certificate_versionretrieves a specific version of a certificate.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClientcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)certificate=certificate_client.get_certificate_version(certificate_name="cert-name",version="cert-version")print(certificate.name)print(certificate.properties.version)Update properties of an existing certificateupdate_certificate_propertiesupdates a certificate previously stored in the Key Vault.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClientcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)# we will now disable the certificate for further useupdated_certificate=certificate_client.update_certificate_properties(certificate_name="cert-name",enabled=False)print(updated_certificate.name)print(updated_certificate.properties.enabled)Delete a certificatebegin_delete_certificaterequests Key Vault delete a certificate, 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 certificate as soon as possible. Whensoft-deleteis disabled,begin_delete_certificateitself is permanent.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClientcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)deleted_certificate_poller=certificate_client.begin_delete_certificate("cert-name")deleted_certificate=deleted_certificate_poller.result()print(deleted_certificate.name)print(deleted_certificate.deleted_on)List properties of certificateslist_properties_of_certificateslists the properties of all certificates in the specified Key Vault.fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClientcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)certificates=certificate_client.list_properties_of_certificates()forcertificateincertificates:# this list doesn't include versions of the certificatesprint(certificate.name)Async operationsThis 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.certificates.aioimportCertificateClientcredential=DefaultAzureCredential()# call close when the client and credential are no longer neededclient=CertificateClient(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=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)asyncwithclient:asyncwithcredential:...Asynchronously create a certificatecreate_certificatecreates a certificate to be stored in the Azure Key Vault. If a certificate with the same name already exists, 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. Awaitingcreate_certificatereturns your created certificate if creation
is successful, and aCertificateOperationif it is not.fromazure.identity.aioimportDefaultAzureCredentialfromazure.keyvault.certificates.aioimportCertificateClientfromazure.keyvault.certificatesimportCertificatePolicycredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)create_certificate_result=awaitcertificate_client.create_certificate(certificate_name="cert-name",policy=CertificatePolicy.get_default())print(create_certificate_result)Asynchronously list properties of certificateslist_properties_of_certificateslists all the properties of the certificates in the client's vault:fromazure.identity.aioimportDefaultAzureCredentialfromazure.keyvault.certificates.aioimportCertificateClientcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)certificates=certificate_client.list_properties_of_certificates()asyncforcertificateincertificates:print(certificate.name)TroubleshootingSee theazure-keyvault-certificatestroubleshooting 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,CertificateClientraisesResourceNotFoundError:fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.certificatesimportCertificateClientfromazure.core.exceptionsimportResourceNotFoundErrorcredential=DefaultAzureCredential()certificate_client=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential)try:certificate_client.get_certificate("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.certificatesimportCertificateClientimportsysimportlogging# 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 levelclient=CertificateClient(vault_url="https://my-key-vault.vault.azure.net/",credential=credential,logging_enable=True)Network trace logging can also be enabled for any single operation:certificate=certificate_client.get_certificate(certificate_name="cert-name",logging_enable=True)Next stepsSeveral samples are available in the Azure SDK for Python GitHub repository. These samples provide example code for additional Key Vault scenarios:Create/get/update/delete certificates(async version)Back up and recover certificates(async version)Import PKCS#12 (PFX) and PEM-formatted certificates into Key Vault(async version)List certificates(async version)Recover and purge certificates(async version)Manage certificate issuers(async version)Manage certificate contacts(async version)Extract a certificate's private key(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.5Breaking ChangesThese changes do not impact the API of stable versions such as 4.7.0. Only code written against a beta version such as 4.8.0b2 may be affected.RemovedCertificateProperties.x509_thumbprint_string. To get the certificate's thumbprint in hex, useCertificateProperties.x509_thumbprint.hex()or print theCertificatePropertiesinstance.Bugs 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)Key Vault API version7.5is now the defaultUpdated minimumazure-coreversion to 1.29.5Droppedazure-commonrequirement4.8.0b3 (2023-11-03)Features AddedAdded support for service API version7.5-preview.1Other ChangesKey Vault API version7.5-preview.1is now the default4.8.0b2 (2023-07-11)Features AddedAddedCertificateProperties.x509_thumbprint_stringto return the hexadecimal string representation of the SHA-1 hash
of the certificate (#30166)4.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)Bugs FixedThe type hints forKeyVaultCertificate.cerandDeletedCertificate.cerare nowOptional[bytearray]instead ofOptional[bytes](#28959)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 aKeyVaultCertificateIdentifier(#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)Bugs FixedKeyTypenow ignores casing during declaration, which resolves a scenario where Key Vault
keys created with non-standard casing could not be fetched with the SDK
(#22797)Other 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)Other 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+.ChangedKey Vault API version 7.2 is now the defaultUpdated minimummsrestversion to 0.6.21Theissuer_nameparameter forCertificatePolicyis now optionalAddedAdded classKeyVaultCertificateIdentifierthat parses out a full ID returned by Key Vault,
so users can easily access the certificate'sname,vault_url, andversion.4.2.1 (2020-09-08)FixedCorrect typing for paging methodsFixed incompatibility issues with API version 2016-10-014.2.0 (2020-08-11)FixedFixed anAttributeErrorduringget_certificate_versionimport_certificateno longer raisesAttributeErrorwhen thepolicykeyword argument isn't passedValues 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)CertificateClientinstances have aclosemethod which closes opened
sockets. Used as a context manager, aCertificateClientcloses opened sockets
on exit. (#9906)Pollers no longer sleep after operation completion
(#9991)4.0.1 (2020-02-11)azure.keyvault.certificatesdefines__version__Updatedmsrestrequirement to >=0.6.0Challenge authentication policy requires TLS
(#9457)Methods no longer raise the internal errorKeyVaultErrorException(#9690)4.0.0 (2020-01-08)First GA release4.0.0b7 (2019-12-17)Challenge authentication policy preserves request options
(#8999)Addedvault_urlproperty toCertificateOperationRemovedid,expires_on,not_before, andrecover_levelproperties fromCertificatePolicyRemovedvault_urlproperty fromCertificateIssuerRemovedvault_urlproperty fromIssuerProperties4.0.0b6 (2019-12-04)Updatedmsrestrequirement to >=0.6.0Renamedget_policytoget_certificate_policyRenamedupdate_policytoupdate_certificate_policyRenamedcreate_contactstoset_contactsRenamed parameteradmin_detailsofcreate_issuerandupdate_issuertoadmin_contactsRenamed allnameparameters to include the name of the object whose name we are referring to.
For example, thenameparameter ofget_certificateis nowcertificate_nameRenamedAdministratorDetailstoAdministratorContactRenamed theekusproperty ofCertificatePolicytoenhanced_key_usageRenamed thecurveproperty ofCertificatePolicytokey_curve_nameRenamed thesan_upnsproperty ofCertificatePolicytosan_user_principal_namesMade thesubject_nameproperty ofCertificatePolicya kwarg and renamed it tosubjectRenamed thedeleted_dateproperty ofDeletedCertificatetodeleted_onRemoved theissuer_propertiesproperty fromCertificateIssuerand added theproviderproperty
directly ontoCertificateIssuerRenamed propertyadmin_detailsofCertificateIssuertoadmin_contactsRenamed thethumbprintproperty ofCertificatePropertiestox509_thumbprintAddedWellKnownIssuerNamesenum class that holds popular issuer namesRenamedSecretContentTypeenum class toCertificateContentType4.0.0b5 (2019-11-01)Removed redundant methodget_pending_certificate_signing_request(). A pending CSR can be retrieved viaget_certificate_operation().Renamed the sync methodcreate_certificatetobegin_create_certificateRenamedrestore_certificatetorestore_certificate_backupRenamedget_certificatetoget_certificate_versionRenamedget_certificate_with_policytoget_certificateRenamedlist_certificatestolist_properties_of_certificatesRenamedlist_properties_of_issuerstolist_properties_of_issuersRenamedlist_certificate_versionstolist_properties_of_certificate_versionscreate_certificatenow has policy as a required parameterAll optional positional parameters besidesversionhave been moved to kwargsRenamed sync methoddelete_certificatetobegin_delete_certificateRenamed sync methodrecover_certificatetobegin_recover_deleted_certificateRenamed async methodrecover_certificatetorecover_deleted_certificateThe sync methodbegin_delete_certificateand asyncdelete_certificatenow return pollers that return aDeletedCertificateThe sync methodbegin_recover_deleted_certificateand asyncrecover_deleted_certificatenow return pollers that return aKeyVaultCertificateRenamed enumActionTypetoCertificatePolicyActionRenamedCertificatetoKeyVaultCertificateRenamedContacttoCertificateContactRenamedIssuertoCertificateIssuerRenamedCertificateErrortoCertificateOperationErrorRenamedexpiresproperty ofCertificatePropertiesandCertificatePolicytoexpires_onRenamedcreatedproperty ofCertificateProperties,CertificatePolicy, andCertificateIssuertocreated_onRenamedupdatedproperty ofCertificateProperties,CertificatePolicy, andCertificateIssuertoupdated_onThevault_endpointparameter ofCertificateClienthas been renamed tovault_urlThe propertyvault_endpointhas been renamed tovault_urlin all modelsCertificatePolicynow has a public class methodget_defaultallowing users to get the defaultCertificatePolicyLogging can now be enabled properly on the client level4.0.0b4 (2019-10-08)EnumsJsonWebKeyCurveNameandJsonWebKeyTypehave been renamed toKeyCurveNameandKeyType, respectively.Both async and sync versions ofcreate_certificatenow return pollers that return the createdCertificateif creation is successful,
and aCertificateOperationif not.Certificatenow has attributeproperties, which holds certain properties of the
certificate, such asversion. This changes the shape of theCertificatetype,
as certain properties ofCertificate(such asversion) have to be accessed
through thepropertiesproperty.update_certificatehas been renamed toupdate_certificate_propertiesThevault_urlparameter ofCertificateClienthas been renamed tovault_endpointThe propertyvault_urlhas been renamed tovault_endpointin all models4.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 forazure-keyvault. Applications
using that library would require code changes to useazure-keyvault-certificates.
This package'sdocumentationandsamplesdemonstrate the new API.Breaking changes fromazure-keyvault:Packages scoped by functionalityazure-keyvault-certificatescontains a client for certificate operationsClient instances are scoped to vaults (an instance interacts with one vault
only)Authentication usingazure-identitycredentialssee this package'sdocumentation, and theAzure Identity documentationfor more informationNew Features:Distributed tracing framework OpenCensus is now supportedAsynchronous API supported on Python 3.5.3+theazure.keyvault.certificates.aionamespace contains an async equivalent of
the synchronous client inazure.keyvault.certificatesAsync clients useaiohttpfor transport
by default. Seeazure-core documentationfor more information about using other transports.