Microsoft Azure Key Vault Administration Client Library for Python
Note: The Administration library only works with Managed HSM – functions targeting a Key Vault will fail.
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 to https://github.com/Azure/azure-sdk-for-python/issues/20691. Python 3.7 or later is required to use this package. For more details, please refer to Azure SDK for Python version support policy.
Install azure-keyvault-administration and azure-identity with pip:
pip install azure-keyvault-administration azure-identity
azure-identity is used for Azure Active Directory authentication as demonstrated below.
In order to interact with the Azure Key Vault service, you will need an instance of either a KeyVaultAccessControlClient or KeyVaultBackupClient, as well as a vault url (which you may see as "DNS Name" in the Azure Portal) 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.
After configuring your environment for the DefaultAzureCredential to use a suitable method of authentication, you can do the following to create an access control client (replacing the value of vault_url
with your Managed HSM's URL):
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultAccessControlClient
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
NOTE: For an asynchronous client, import
azure.keyvault.administration.aio
'sKeyVaultAccessControlClient
instead.
After configuring your environment for the DefaultAzureCredential to use a suitable method of authentication, you can do the following to create a backup client (replacing the value of vault_url
with your Managed HSM's URL):
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultBackupClient
credential = DefaultAzureCredential()
client = KeyVaultBackupClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
NOTE: For an asynchronous client, import
azure.keyvault.administration.aio
'sKeyVaultBackupClient
instead.
After configuring your environment for the DefaultAzureCredential to use a suitable method of authentication, you can do the following to create a settings client (replacing the value of vault_url
with your Managed HSM's URL):
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultSettingsClient
credential = DefaultAzureCredential()
client = KeyVaultSettingsClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
NOTE: For an asynchronous client, import
azure.keyvault.administration.aio
'sKeyVaultSettingsClient
instead.
A 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.
A role assignment is the association of a role definition to a service principal. They can be created, listed, fetched individually, and deleted.
A KeyVaultAccessControlClient
manages role definitions and role assignments.
A KeyVaultBackupClient
performs full key backups, full key restores, and selective key restores.
A KeyVaultSettingsClient
manages Managed HSM account settings.
This section contains code snippets covering common tasks:
List the role definitions available for assignment.
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultAccessControlClient, KeyVaultRoleScope
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
# this will list all role definitions available for assignment
role_definitions = client.list_role_definitions(KeyVaultRoleScope.GLOBAL)
for definition in role_definitions:
print(definition.id)
print(definition.role_name)
print(definition.description)
set_role_definition
can be used to either create a custom role definition or update an existing definition with the specified name.
import uuid
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import (
KeyVaultAccessControlClient,
KeyVaultDataAction,
KeyVaultPermission,
KeyVaultRoleScope
)
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
# create a custom role definition
permissions = [KeyVaultPermission(allowed_data_actions=[KeyVaultDataAction.READ_HSM_KEY])]
created_definition = client.set_role_definition(KeyVaultRoleScope.GLOBAL, permissions=permissions)
# update the custom role definition
permissions = [
KeyVaultPermission(allowed_data_actions=[], denied_data_actions=[KeyVaultDataAction.READ_HSM_KEY])
]
updated_definition = client.set_role_definition(
KeyVaultRoleScope.GLOBAL, permissions=permissions, role_name=created_definition.name
)
# get the custom role definition
definition = client.get_role_definition(KeyVaultRoleScope.GLOBAL, role_name=definition_name)
# delete the custom role definition
deleted_definition = client.delete_role_definition(KeyVaultRoleScope.GLOBAL, role_name=definition_name)
Before creating a new role assignment in the next snippet, list all of the current role assignments:
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultAccessControlClient, KeyVaultRoleScope
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
# this will list all role assignments
role_assignments = client.list_role_assignments(KeyVaultRoleScope.GLOBAL)
for assignment in role_assignments:
print(assignment.name)
print(assignment.principal_id)
print(assignment.role_definition_id)
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 retrieved list of role definitions for the former, and an assignment's principal_id
from the list retrieved in the above snippet for the latter.
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultAccessControlClient, KeyVaultRoleScope
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(
vault_url="https://my-managed-hsm-name.managedhsm.azure.net/",
credential=credential
)
# Replace <role-definition-id> with the id of a definition from the fetched list from an earlier example
role_definition_id = "<role-definition-id>"
# Replace <service-principal-object-id> with the principal_id of an assignment returned from the previous example
principal_id = "<service-principal-object-id>"
# first, let's create the role assignment
role_assignment = client.create_role_assignment(KeyVaultRoleScope.GLOBAL, role_definition_id, principal_id)
print(role_assignment.name)
print(role_assignment.principal_id)
print(role_assignment.role_definition_id)
# now, we get it
role_assignment = client.get_role_assignment(KeyVaultRoleScope.GLOBAL, role_assignment.name)
print(role_assignment.name)
print(role_assignment.principal_id)
print(role_assignment.role_definition_id)
# finally, we delete this role assignment
role_assignment = client.delete_role_assignment(KeyVaultRoleScope.GLOBAL, role_assignment.name)
print(role_assignment.name)
print(role_assignment.principal_id)
print(role_assignment.role_definition_id)
Back up your entire collection of keys. The backing store for full key backups is a blob storage container using Shared Access Signature authentication.
For more details on creating a SAS token using the BlobServiceClient
, see the sample here.
Alternatively, it is possible to generate a SAS token in Storage Explorer
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultBackupClient
credential = DefaultAzureCredential()
client = KeyVaultBackupClient(vault_url="https://my-managed-hsm-name.managedhsm.azure.net/", credential=credential)
# blob storage container URL, for example https://<account name>.blob.core.windows.net/backup
blob_storage_url = "<your-blob-storage-url>"
sas_token = "<your-sas-token>" # replace with a sas token to your storage account
# Backup is a long-running operation. The client returns a poller object whose result() method
# blocks until the backup is complete, then returns an object representing the backup operation.
backup_poller = client.begin_backup(blob_storage_url, sas_token)
backup_operation = backup_poller.result()
# this is the Azure Storage Blob URL of the backup
print(backup_operation.folder_url)
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 azure_storage_blob_container_uri
from the above snippet.
For more details on creating a SAS token using the BlobServiceClient
, see the sample here.
Alternatively, it is possible to generate a SAS token in Storage Explorer
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultBackupClient
credential = DefaultAzureCredential()
client = KeyVaultBackupClient(vault_url="https://my-managed-hsm-name.managedhsm.azure.net/", credential=credential)
sas_token = "<your-sas-token>" # replace with a sas token to your storage account
# URL to a storage blob, for example https://<account name>.blob.core.windows.net/backup/mhsm-account-2020090117323313
blob_url = "<your-blob-url>"
# Restore is a long-running operation. The client returns a poller object whose wait() method
# blocks until the restore is complete.
restore_poller = client.begin_restore(blob_url, sas_token)
restore_poller.wait()
See the azure-keyvault-administration
troubleshooting guide
for details on how to diagnose various failure scenarios.
Key Vault clients raise exceptions defined in azure-core. For example, if you try to get a role assignment that doesn't exist, KeyVaultAccessControlClient raises ResourceNotFoundError:
from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultAccessControlClient
from azure.core.exceptions import ResourceNotFoundError
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(vault_url="https://my-managed-hsm-name.managedhsm.azure.net/", credential=credential)
try:
client.get_role_assignment("/", "which-does-not-exist")
except ResourceNotFoundError as e:
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.
Several samples are available in the Azure SDK for Python GitHub repository. These samples provide example code for additional Key Vault scenarios:
File | Description |
---|---|
access_control_operations.py | create/update/delete role definitions and role assignments |
access_control_operations_async.py | create/update/delete role definitions and role assignments with an async client |
backup_restore_operations.py | full backup and restore |
backup_restore_operations_async.py | full backup and restore with an async client |
settings_operations.py | list and update Key Vault settings |
settings_operations_async.py | list and update Key Vault settings with an async client |
For more extensive documentation on Azure Key Vault, see the API reference documentation.
For more extensive documentation on Managed HSM, see the service documentation.
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.
7.4
send_request
method that can be used to send custom requests using the
client's existing pipeline (#25172)KeyVaultSettingsClient
s for getting and updating Managed HSM settingsKeyVaultSetting
class has a getboolean
method that will return the setting's value
as a bool
, if possible,
and raise a ValueError
otherwiseThese 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_setting
now accepts a single setting
argument (a KeyVaultSetting
instance)
instead of a name
and value
KeyVaultSetting
model's type
parameter and attribute have been renamed to setting_type
SettingType
enum has been renamed to KeyVaultSettingType
7.4
is now the defaultazure-core
version to 1.24.0msrest
requirementsix
requirementisodate>=0.6.1
(isodate
was required by msrest
)typing-extensions>=4.0.1
KeyVaultSettingsClient
s for getting and updating Managed HSM settings.7.4-preview.1
7.4-preview.1
is now the defaultazure-core
version to 1.24.0msrest
requirementsix
requirementisodate>=0.6.1
(isodate
was required by msrest
)typing-extensions>=4.0.1
verify_challenge_resource=False
to client constructors to disable.
See https://aka.ms/azsdk/blog/vault-uri for more information.azure-identity
1.8.0 or newer (#20698)azure-core
version to 1.20.0get_token
calls during challenge
authentication requests now pass in a tenant_id
keyword argument
(#20698). See
https://aka.ms/azsdk/python/identity/tokencredential for more details on how to integrate
this parameter if get_token
is implemented by a custom credential.azure-core
version to 1.20.0get_token
calls during challenge
authentication requests now pass in a tenant_id
keyword argument
(#20698)azure-identity
1.7.1 or newer
(#20698)azure-core
version to 1.15.0KeyVaultAccessControlClient.delete_role_assignment
and
.delete_role_definition
no longer raise an error when the resource to be
deleted is not foundKeyVaultAccessControlClient.set_role_definition
accepts an optional
assignable_scopes
keyword-only argumentKeyVaultAccessControlClient.delete_role_assignment
and
.delete_role_definition
return NoneKeyVaultAccessControlClient.set_role_definition
.
permissions
is now an optional keyword-only argumentBackupOperation
to KeyVaultBackupResult
, and removed all but
its folder_url
propertyRestoreOperation
and SelectiveKeyRestoreOperation
classesKeyVaultBackupClient.begin_selective_restore
. To restore a
single key, pass the key's name to KeyVaultBackupClient.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)
KeyVaultBackupClient.get_backup_status
and .get_restore_status
. Use
the pollers returned by KeyVaultBackupClient.begin_backup
and .begin_restore
to check whether an operation has completedKeyVaultRoleAssignment
's principal_id
, role_definition_id
, and scope
are now properties of a properties
property# before (4.0.0b3):
print(KeyVaultRoleAssignment.scope)
# after:
print(KeyVaultRoleAssignment.properties.scope)
KeyVaultPermission
properties:
allowed_actions
-> actions
denied_actions
-> not_actions
allowed_data_actions
-> data_actions
denied_data_actions
-> denied_data_actions
role_assignment_name
to name
in
KeyVaultAccessControlClient.create_role_assignment
, .delete_role_assignment
,
and .get_role_assignment
role_definition_name
to name
in
KeyVaultAccessControlClient.delete_role_definition
and .get_role_definition
role_scope
to scope
in KeyVaultAccessControlClient
methodsKeyVaultAccessControlClient
supports managing custom role definitionsKeyVaultBackupClient.begin_full_backup()
to .begin_backup()
KeyVaultBackupClient.begin_full_restore()
to .begin_restore()
BackupOperation.azure_storage_blob_container_uri
to .folder_url
id
property of BackupOperation
, RestoreOperation
, and
SelectiveKeyRestoreOperation
to job_id
blob_storage_uri
parameters of KeyVaultBackupClient.begin_restore()
and .begin_selective_restore()
to folder_url
folder_name
parameter from
KeyVaultBackupClient.begin_restore()
and .begin_selective_restore()
(the
folder_url
parameter contains the folder name)KeyVaultPermission
attributes:
actions
-> allowed_actions
data_actions
-> allowed_data_actions
not_actions
-> denied_actions
not_data_actions
-> denied_data_actions
KeyVaultRoleAssignment.assignment_id
to .role_assignment_id
KeyVaultRoleScope
enum values:
global_value
-> GLOBAL
keys_value
-> KEYS
KeyVaultBackupClient.get_backup_status
and .get_restore_status
enable
checking the status of a pending operation by its job ID
(#13718)role_assignment_name
parameter of
KeyVaultAccessControlClient.create_role_assignment
is now an optional
keyword-only argument. When this argument isn't passed, the client will
generate a name for the role assignment.
(#13512)KeyVaultAccessControlClient
performs role-based access control operationsKeyVaultBackupClient
performs full vault backup and full and selective
restore operations