Package: azure-keyvault-administration
Azure Key Vault Administration client library for PythonNote:The Administration library only works withManaged HSM– functions targeting a Key Vault will fail.Azure Key Vault helps solve the following problems:Vault administration (this library) - role-based access control (RBAC), and vault-level backup and restore optionsCryptographic 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 secretsCertificate management
(azure-keyvault-certificates) -
create, manage, and deploy public and private SSL/TLS certificatesSource 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-administrationandazure-identitywithpip:pipinstallazure-keyvault-administrationazure-identityazure-identityis used for Azure Active Directory
authentication as demonstrated below.PrerequisitesAnAzure subscriptionPython 3.8 or laterAn existingKey Vault Managed HSM. 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 either aKeyVaultAccessControlClientorKeyVaultBackupClient, as well as avault url(which you may see as "DNS Name" in the Azure Portal) 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 identityfor authentication in production environments.Seeazure-identitydocumentation for more information about other methods of authentication and their corresponding credential types.Create a KeyVaultAccessControlClientAfter configuring your environment for theDefaultAzureCredentialto use a suitable method of authentication, you can do the following to create an access control client (replacing the value ofvault_urlwith your Managed HSM's URL):fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.administrationimportKeyVaultAccessControlClientMANAGED_HSM_URL=os.environ["MANAGED_HSM_URL"]credential=DefaultAzureCredential()client=KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL,credential=credential)NOTE:For an asynchronous client, importazure.keyvault.administration.aio'sKeyVaultAccessControlClientinstead.Create a KeyVaultBackupClientAfter configuring your environment for theDefaultAzureCredentialto use a suitable method of authentication, you can do the following to create a backup client (replacing the value ofvault_urlwith your Managed HSM's URL):fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.administrationimportKeyVaultBackupClientMANAGED_HSM_URL=os.environ["MANAGED_HSM_URL"]credential=DefaultAzureCredential()client=KeyVaultBackupClient(vault_url=MANAGED_HSM_URL,credential=credential)NOTE:For an asynchronous client, importazure.keyvault.administration.aio'sKeyVaultBackupClientinstead.Create a KeyVaultSettingsClientAfter configuring your environment for theDefaultAzureCredentialto use a suitable method of authentication, you can do the following to create a settings client (replacing the value ofvault_urlwith your Managed HSM's URL):fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.administrationimportKeyVaultSettingsClientMANAGED_HSM_URL=os.environ["MANAGED_HSM_URL"]credential=DefaultAzureCredential()client=KeyVaultSettingsClient(vault_url=MANAGED_HSM_URL,credential=credential)NOTE:For an asynchronous client, importazure.keyvault.administration.aio'sKeyVaultSettingsClientinstead.Key conceptsRole definitionA role definition defines the operations that can be performed, such as read, write, and delete. It can also define the operations that are excluded from allowed operations.A role definition is specified as part of a role assignment.Role assignmentA role assignment is the association of a role definition to a service principal. They can be created, listed, fetched individually, and deleted.KeyVaultAccessControlClientAKeyVaultAccessControlClientmanages role definitions and role assignments.KeyVaultBackupClientAKeyVaultBackupClientperforms full key backups, full key restores, and selective key restores.KeyVaultSettingsClientAKeyVaultSettingsClientmanages Managed HSM account settings.ExamplesThis section contains code snippets covering common tasks:Access controlList all role definitionsSet, get, and delete a role definitionList all role assignmentsCreate, get, and delete a role assignmentBackup and restorePerform a full key backupPerform a full key restorePerform a selective key restoreList all role definitionslist_role_definitionscan be used by aKeyVaultAccessControlClientto list the role definitions available for
assignment.fromazure.keyvault.administrationimportKeyVaultRoleScoperole_definitions=client.list_role_definitions(scope=KeyVaultRoleScope.GLOBAL)fordefinitioninrole_definitions:print(f"Role name:{definition.role_name}; Role definition name:{definition.name}")Set, get, and delete a role definitionset_role_definitioncan be used by aKeyVaultAccessControlClientto either create a custom role definition or update
an existing definition with the specified uniquename(a UUID).fromazure.keyvault.administrationimportKeyVaultDataAction,KeyVaultPermission,KeyVaultRoleScoperole_name="customRole"scope=KeyVaultRoleScope.GLOBALpermissions=[KeyVaultPermission(data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]role_definition=client.set_role_definition(scope=scope,role_name=role_name,permissions=permissions)new_permissions=[KeyVaultPermission(data_actions=[KeyVaultDataAction.READ_HSM_KEY],not_data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]unique_definition_name=role_definition.nameupdated_definition=client.set_role_definition(scope=scope,name=unique_definition_name,role_name=role_name,permissions=new_permissions)get_role_definitioncan be used by aKeyVaultAccessControlClientto fetch a role definition with the specified scope
and unique name.fetched_definition=client.get_role_definition(scope=scope,name=unique_definition_name)delete_role_definitioncan be used by aKeyVaultAccessControlClientto delete a role definition with the specified
scope and unique name.client.delete_role_definition(scope=scope,name=unique_definition_name)List all role assignmentslist_role_assignmentscan be used by aKeyVaultAccessControlClientto list all of the current role assignments.fromazure.keyvault.administrationimportKeyVaultRoleScoperole_assignments=client.list_role_assignments(KeyVaultRoleScope.GLOBAL)forassignmentinrole_assignments:assertassignment.propertiesprint(f"Role assignment name:{assignment.name}")print(f"Principal ID associated with this assignment:{assignment.properties.principal_id}")Create, get, and delete a role assignmentRole assignments assign a role to a service principal. This will require a role definition ID and service principal
object ID. You can use an ID from the retrievedlist of role definitionsfor the former,
and an assignment'sprincipal_idfrom the list retrieved in theabove snippetfor the
latter. Provide these values, and a scope, to aKeyVaultAccessControlClient'screate_role_assignmentmethod.fromazure.keyvault.administrationimportKeyVaultRoleScopescope=KeyVaultRoleScope.GLOBALrole_assignment=client.create_role_assignment(scope=scope,definition_id=definition_id,principal_id=principal_id)print(f"Role assignment{role_assignment.name}created successfully.")get_role_assignmentcan be used by aKeyVaultAccessControlClientto fetch an existing role assignment with the
specified scope and unique name.fetched_assignment=client.get_role_assignment(scope=scope,name=role_assignment.name)assertfetched_assignment.propertiesprint(f"Role assignment for principal{fetched_assignment.properties.principal_id}fetched successfully.")delete_role_assignmentcan be used by aKeyVaultAccessControlClientto delete a role assignment with the specified
scope and unique name.client.delete_role_assignment(scope=scope,name=role_assignment.name)Perform a full key backupTheKeyVaultBackupClientcan be used to back up your entire collection of keys. The backing store for full key
backups is a blob storage container using Shared Access Signature (SAS) authentication.For more details on creating a SAS token using aBlobServiceClientfromazure-storage-blob, refer
to the library'scredential documentation. Alternatively, it is possible togenerate a SAS token in Storage Explorer.CONTAINER_URL=os.environ["CONTAINER_URL"]SAS_TOKEN=os.environ["SAS_TOKEN"]backup_result:KeyVaultBackupResult=client.begin_backup(CONTAINER_URL,sas_token=SAS_TOKEN).result()print(f"Azure Storage Blob URL of the backup:{backup_result.folder_url}")Note that thebegin_backupmethod returns a poller. Callingresult()on this poller returns aKeyVaultBackupResultcontaining information about the backup. Callingwait()on the poller will instead block until
the operation is complete without returning an object.Perform a full key restoreTheKeyVaultBackupClientcan be used to restore your entire collection of keys from a backup. The data source for a
full key restore is a storage blob accessed using Shared Access Signature authentication. You will also need the URL of
the backup (KeyVaultBackupResult.folder_url) from theabove snippet.For more details on creating a SAS token using aBlobServiceClientfromazure-storage-blob, refer
to the library'scredential documentation. Alternatively, it is possible togenerate a SAS token in Storage Explorer.SAS_TOKEN=os.environ["SAS_TOKEN"]# `backup_result` is the KeyVaultBackupResult returned by `begin_backup`client.begin_restore(backup_result.folder_url,sas_token=SAS_TOKEN).wait()print("Vault restored successfully.")Note that thebegin_restoremethod returns a poller. Unlike the poller returned bybegin_backup, this poller'sresultmethod returnsNone; therefore, callingwait()is functionally the same.Perform a selective key restoreTo restore a single key from a backed up vault instead of all keys, provide the key name as akey_nameargument to thebegin_restoremethodshown above.TroubleshootingSee theazure-keyvault-administrationtroubleshooting 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 role assignment that doesn't exist, KeyVaultAccessControlClient
raisesResourceNotFoundError:fromazure.identityimportDefaultAzureCredentialfromazure.keyvault.administrationimportKeyVaultAccessControlClientfromazure.core.exceptionsimportResourceNotFoundErrorcredential=DefaultAzureCredential()client=KeyVaultAccessControlClient(vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",credential=credential)try:client.get_role_assignment("/","which-does-not-exist")exceptResourceNotFoundErrorase:print(e.message)Clients from the Administration library can only be used to perform operations on a managed HSM, so attempting to do so on a Key Vault will raise an error.Next stepsSeveral samples are available in the Azure SDK for Python GitHub repository. These samples provide example code for additional Key Vault scenarios:Create/update/delete role definitions and role assignments(async version)Full backup and restore(async version)List and update Key Vault settings(async version)Additional documentationFor more extensive documentation on Azure Key Vault, see theAPI reference documentation.For more extensive documentation on Managed HSM, see theservice 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.4.0 (2024-02-22)Features AddedAdded support for service API version7.5(From 4.4.0b2)KeyVaultBackupClient.begin_backupandKeyVaultBackupClient.begin_restorenow accept ause_managed_identitykeyword-only argument to enable authentication via Managed IdentityBugs Fixed(From 4.4.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.Key Vault API version7.5is now the defaultUpdated minimumazure-coreversion to 1.29.5Droppedazure-commonrequirement4.4.0b2 (2023-11-03)Features AddedAdded support for service API version7.5-preview.1KeyVaultBackupClient.begin_backupandKeyVaultBackupClient.begin_restorenow accept ause_managed_identitykeyword-only argument to enable authentication via Managed IdentityOther ChangesKey Vault API version7.5-preview.1is now the default4.4.0b1 (2023-05-16)Bugs FixedToken requests made during AD FS authentication no longer specify an erroneous "adfs" tenant ID
(#29888)4.3.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)(From 4.3.0b1) Added sync and asyncKeyVaultSettingsClients for getting and updating Managed HSM settingsTheKeyVaultSettingclass has agetbooleanmethod that will return the setting'svalueas abool, if possible,
and raise aValueErrorotherwiseBreaking ChangesThese changes do not impact the API of stable versions such as 4.2.0. Only code written against a beta version such as 4.3.0b1 may be affected.KeyVaultSettingsClient.update_settingnow accepts a singlesettingargument (aKeyVaultSettinginstance)
instead of anameandvalueTheKeyVaultSettingmodel'stypeparameter and attribute have been renamed tosetting_typeTheSettingTypeenum has been renamed toKeyVaultSettingTypeOther ChangesKey Vault API version7.4is now the default(From 4.3.0b1) Python 3.6 is no longer supported. Please use Python version 3.7 or later.(From 4.3.0b1) Updated minimumazure-coreversion to 1.24.0(From 4.3.0b1) Droppedmsrestrequirement(From 4.3.0b1) Droppedsixrequirement(From 4.3.0b1) Added requirement forisodate>=0.6.1(isodatewas required bymsrest)(From 4.3.0b1) Added requirement fortyping-extensions>=4.0.14.3.0b1 (2022-11-15)Features AddedAdded sync and asyncKeyVaultSettingsClients for getting and updating Managed HSM settings.Added support for service API version7.4-preview.1Other ChangesPython 3.6 is no longer supported. Please use Python version 3.7 or later.Key Vault API version7.4-preview.1is now the defaultUpdated minimumazure-coreversion to 1.24.0DroppedmsrestrequirementDroppedsixrequirementAdded requirement forisodate>=0.6.1(isodatewas required bymsrest)Added requirement fortyping-extensions>=4.0.14.2.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.1.1 (2022-08-11)Other ChangesDocumentation improvements
(#25039)4.1.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)Other Changes(From 4.1.0b3) Python 2.7 is no longer supported. Please use Python version 3.6 or later.(From 4.1.0b3) Updated minimumazure-coreversion to 1.20.0(From 4.1.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.1.0b3 (2022-02-08)Other ChangesPython 2.7 is no longer supported. Please use Python version 3.6 or later.Updated minimumazure-coreversion to 1.20.0(From 4.1.0b2) To support multi-tenant authentication,get_tokencalls during challenge
authentication requests now pass in atenant_idkeyword argument
(#20698)4.1.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.1.0b1 (2021-09-09)Features AddedKey Vault API version 7.3-preview is now the default4.0.0 (2021-06-22)ChangedKey Vault API version 7.2 is now the defaultKeyVaultAccessControlClient.delete_role_assignmentand.delete_role_definitionno longer raise an error  when the resource to be
deleted is not foundRaised minimum azure-core version to 1.11.0AddedKeyVaultAccessControlClient.set_role_definitionaccepts an optionalassignable_scopeskeyword-only argumentBreaking ChangesKeyVaultAccessControlClient.delete_role_assignmentand.delete_role_definitionreturn NoneChanged parameter order inKeyVaultAccessControlClient.set_role_definition.permissionsis now an optional keyword-only argumentRenamedBackupOperationtoKeyVaultBackupResult, and removed all but
itsfolder_urlpropertyRemovedRestoreOperationandSelectiveKeyRestoreOperationclassesRemovedKeyVaultBackupClient.begin_selective_restore. To restore a
single key, pass the key's name toKeyVaultBackupClient.begin_restore:# before (4.0.0b3):
client.begin_selective_restore(folder_url, sas_token, key_name)

# after:
client.begin_restore(folder_url, sas_token, key_name=key_name)RemovedKeyVaultBackupClient.get_backup_statusand.get_restore_status. Use
the pollers returned byKeyVaultBackupClient.begin_backupand.begin_restoreto check whether an operation has completedKeyVaultRoleAssignment'sprincipal_id,role_definition_id, andscopeare now properties of apropertiesproperty# before (4.0.0b3):
print(KeyVaultRoleAssignment.scope)

# after:
print(KeyVaultRoleAssignment.properties.scope)RenamedKeyVaultPermissionproperties:allowed_actions->actionsdenied_actions->not_actionsallowed_data_actions->data_actionsdenied_data_actions->denied_data_actionsRenamed argumentrole_assignment_nametonameinKeyVaultAccessControlClient.create_role_assignment,.delete_role_assignment,
and.get_role_assignmentRenamed argumentrole_definition_nametonameinKeyVaultAccessControlClient.delete_role_definitionand.get_role_definitionRenamed argumentrole_scopetoscopeinKeyVaultAccessControlClientmethods4.0.0b3 (2021-02-09)AddedKeyVaultAccessControlClientsupports managing custom role definitionsBreaking ChangesRenamedKeyVaultBackupClient.begin_full_backup()to.begin_backup()RenamedKeyVaultBackupClient.begin_full_restore()to.begin_restore()RenamedBackupOperation.azure_storage_blob_container_urito.folder_urlRenamedidproperty ofBackupOperation,RestoreOperation, andSelectiveKeyRestoreOperationtojob_idRenamedblob_storage_uriparameters ofKeyVaultBackupClient.begin_restore()and.begin_selective_restore()tofolder_urlRemoved redundantfolder_nameparameter fromKeyVaultBackupClient.begin_restore()and.begin_selective_restore()(thefolder_urlparameter contains the folder name)RenamedKeyVaultPermissionattributes:actions->allowed_actionsdata_actions->allowed_data_actionsnot_actions->denied_actionsnot_data_actions->denied_data_actionsRenamedKeyVaultRoleAssignment.assignment_idto.role_assignment_idRenamedKeyVaultRoleScopeenum values:global_value->GLOBALkeys_value->KEYS4.0.0b2 (2020-10-06)AddedKeyVaultBackupClient.get_backup_statusand.get_restore_statusenable
checking the status of a pending operation by its job ID
(#13718)Breaking ChangesTherole_assignment_nameparameter ofKeyVaultAccessControlClient.create_role_assignmentis now an optional
keyword-only argument. When this argument isn't passed, the client will
generate a name for the role assignment.
(#13512)4.0.0b1 (2020-09-08)AddedKeyVaultAccessControlClientperforms role-based access control operationsKeyVaultBackupClientperforms full vault backup and full and selective
restore operations