Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

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:

  • Vault administration (this library) - role-based access control (RBAC), and vault-level backup and restore options
  • Cryptographic key management (azure-keyvault-keys) - create, store, and control access to the keys used to encrypt your data
  • Secrets management (azure-keyvault-secrets) - securely store and control access to tokens, passwords, certificates, API keys, and other secrets
  • Certificate management (azure-keyvault-certificates) - create, manage, and deploy public and private SSL/TLS certificates

Source code | Package (PyPI) | Package (Conda) | API reference documentation | Product documentation | Samples

Disclaimer

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.9 or later is required to use this package. For more details, please refer to Azure SDK for Python version support policy.

Getting started

Install packages

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.

Prerequisites

Authenticate the client

In order to interact with the Azure Key Vault service, you will need an instance of either a KeyVaultAccessControlClient, KeyVaultBackupClient, KeyVaultSettingsClient, or KeyVaultEkmClient 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.

Create a KeyVaultAccessControlClient

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

MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
credential = DefaultAzureCredential()
client = KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL, credential=credential)

NOTE: For an asynchronous client, import azure.keyvault.administration.aio's KeyVaultAccessControlClient instead.

Create a KeyVaultBackupClient

After creating a user-assigned managed identity and granting it access to your Managed HSM, you can do the following to create a backup client (setting the value of CLIENT_ID to your managed identity's client ID):

from azure.identity import ManagedIdentityCredential
from azure.keyvault.administration import KeyVaultBackupClient

MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
MANAGED_IDENTITY_CLIENT_ID = os.environ["CLIENT_ID"]
credential = ManagedIdentityCredential(client_id=MANAGED_IDENTITY_CLIENT_ID)
client = KeyVaultBackupClient(vault_url=MANAGED_HSM_URL, credential=credential)

Using the ManagedIdentityCredential is preferred in order to enable authenticating backup and restore operations with Managed Identity. Any other azure-identity credential could be provided instead if SAS tokens are used in these operations.

See azure-identity documentation for more information on Managed Identity authentication.

NOTE: For an asynchronous client, import azure.keyvault.administration.aio's KeyVaultBackupClient instead.

Create a KeyVaultSettingsClient

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

MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
credential = DefaultAzureCredential()
client = KeyVaultSettingsClient(vault_url=MANAGED_HSM_URL, credential=credential)

NOTE: For an asynchronous client, import azure.keyvault.administration.aio's KeyVaultSettingsClient instead.

Create a KeyVaultEkmClient

After configuring your environment for the DefaultAzureCredential to use a suitable method of authentication, you can do the following to create an EKM client (replacing the value of vault_url with your Managed HSM's URL):

from azure.identity import DefaultAzureCredential
from azure.keyvault.administration import KeyVaultEkmClient

MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
credential = DefaultAzureCredential()
client = KeyVaultEkmClient(vault_url=MANAGED_HSM_URL, credential=credential)

NOTE: For an asynchronous client, import azure.keyvault.administration.aio's KeyVaultEkmClient instead.

Key concepts

Role definition

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.

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.

KeyVaultAccessControlClient

A KeyVaultAccessControlClient manages role definitions and role assignments.

KeyVaultBackupClient

A KeyVaultBackupClient performs full key backups, full key restores, and selective key restores.

Pre-Backup Operation

A pre-backup operation represents a long-running operation that checks if it is possible to perform a full key backup.

Backup Operation

A backup operation represents a long-running operation for a full key backup.

Pre-Restore Operation

A pre-restore operation represents a long-running operation that checks if it is possible to perform a full key restore from a backup.

Restore Operation

A restore operation represents a long-running operation for both a full key and selective key restore.

KeyVaultSettingsClient

A KeyVaultSettingsClient manages Managed HSM account settings.

KeyVaultEkmClient

A KeyVaultEkmClient manages the Managed HSM's External Key Manager (EKM) connection and its EKM proxy private endpoints.

EKM Connection

An EKM connection represents the connection of an Azure Managed HSM resource with an external HSM.

EKM Proxy Private Endpoint

An EKM proxy private endpoint lets a Managed HSM reach an EKM proxy through an Azure Private Link Service instead of the public internet. A Managed HSM may have up to two EKM proxy private endpoints. To route an EKM connection through one, set the connection's host to the private endpoint's name and its connectivity_mode to KeyVaultEkmConnectivityMode.PRIVATE_ENDPOINT.

Examples

This section contains code snippets covering common tasks:

List all role definitions

list_role_definitions can be used by a KeyVaultAccessControlClient to list the role definitions available for assignment.

from azure.keyvault.administration import KeyVaultRoleScope

role_definitions = client.list_role_definitions(scope=KeyVaultRoleScope.GLOBAL)
for definition in role_definitions:
    print(f"Role name: {definition.role_name}; Role definition name: {definition.name}")

Set, get, and delete a role definition

set_role_definition can be used by a KeyVaultAccessControlClient to either create a custom role definition or update an existing definition with the specified unique name (a UUID).

from azure.keyvault.administration import KeyVaultDataAction, KeyVaultPermission, KeyVaultRoleScope

role_name = "customRole"
scope = KeyVaultRoleScope.GLOBAL
permissions = [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.name
updated_definition = client.set_role_definition(
    scope=scope, name=unique_definition_name, role_name=role_name, permissions=new_permissions
)

get_role_definition can be used by a KeyVaultAccessControlClient to 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_definition can be used by a KeyVaultAccessControlClient to delete a role definition with the specified scope and unique name.

client.delete_role_definition(scope=scope, name=unique_definition_name)

List all role assignments

list_role_assignments can be used by a KeyVaultAccessControlClient to list all of the current role assignments.

from azure.keyvault.administration import KeyVaultRoleScope

role_assignments = client.list_role_assignments(KeyVaultRoleScope.GLOBAL)
for assignment in role_assignments:
    assert assignment.properties
    print(f"Role assignment name: {assignment.name}")
    print(f"Principal ID associated with this assignment: {assignment.properties.principal_id}")

Create, get, and delete a role assignment

Role 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 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. Provide these values, and a scope, to a KeyVaultAccessControlClient's create_role_assignment method.

from azure.keyvault.administration import KeyVaultRoleScope

scope = KeyVaultRoleScope.GLOBAL
role_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_assignment can be used by a KeyVaultAccessControlClient to fetch an existing role assignment with the specified scope and unique name.

fetched_assignment = client.get_role_assignment(scope=scope, name=role_assignment.name)
assert fetched_assignment.properties
print(f"Role assignment for principal {fetched_assignment.properties.principal_id} fetched successfully.")

delete_role_assignment can be used by a KeyVaultAccessControlClient to delete a role assignment with the specified scope and unique name.

client.delete_role_assignment(scope=scope, name=role_assignment.name)

Run a pre-backup check for a collection of keys

The KeyVaultBackupClient can be used to back up your entire collection of keys. The backing store for full key backups is a blob storage container using either Managed Identity (which is preferred) or Shared Access Signature (SAS) authentication.

If using Managed Identity, first make sure your user-assigned managed identity has the correct access to your Storage account and Managed HSM per the service's guidance.

You can first check if an entire collection of keys can be backed up by using KeyVaultBackupClient.begin_pre_backup.

For more details on creating a SAS token using a BlobServiceClient from azure-storage-blob, refer to the library's credential documentation. Alternatively, it is possible to generate a SAS token in Storage Explorer.

CONTAINER_URL = os.environ["CONTAINER_URL"]

try:
    client.begin_pre_backup(CONTAINER_URL, use_managed_identity=True).wait()
except HttpResponseError as e:
    print(f"A backup cannot be performed: {str(e)}")

print("A full key backup can be successfully performed.")

Note that the begin_pre_backup method returns a poller. Calling wait() on this poller waits for the check to complete. An error will raise if the check failed; otherwise the check will have succeeded.

Perform a full key backup

To actually perform the key backup, you can use KeyVaultBackupClient.begin_backup.

CONTAINER_URL = os.environ["CONTAINER_URL"]

backup_result: KeyVaultBackupResult = client.begin_backup(CONTAINER_URL, use_managed_identity=True).result()
print(f"Azure Storage Blob URL of the backup: {backup_result.folder_url}")

Note that the begin_backup method returns a poller. Calling result() on this poller returns a KeyVaultBackupResult containing information about the backup. Calling wait() on the poller will instead block until the operation is complete without returning an object.

Run a pre-restore check for a collection of keys

The KeyVaultBackupClient can 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 either Managed Identity (which is preferred) or Shared Access Signature (SAS) authentication. You will also need the URL of the backup (KeyVaultBackupResult.folder_url) from the above snippet.

If using Managed Identity, first make sure your user-assigned managed identity has the correct access to your Storage account and Managed HSM per the service's guidance.

You can first check if an entire collection of keys can be restored from a backup by using KeyVaultBackupClient.begin_pre_restore.

For more details on creating a SAS token using a BlobServiceClient from azure-storage-blob, refer to the library's credential documentation. Alternatively, it is possible to generate a SAS token in Storage Explorer.

try:
    client.begin_pre_restore(backup_result.folder_url, use_managed_identity=True).wait()
except HttpResponseError as e:
    print(f"A full restore cannot be performed: {str(e)}")

print("A full key restore can be successfully performed.")

Note that the begin_pre_restore method returns a poller. Calling wait() on this poller waits for the check to complete. An error will raise if the check failed; otherwise the check will have succeeded.

Perform a full key restore

To actually restore your entire collection of keys, you can use KeyVaultBackupClient.begin_restore.

# `backup_result` is the KeyVaultBackupResult returned by `begin_backup`
client.begin_restore(backup_result.folder_url, use_managed_identity=True).wait()
print("Vault restored successfully.")

Note that the begin_restore method returns a poller. Unlike the poller returned by begin_backup, this poller's result method returns None; therefore, calling wait() is functionally the same.

Perform a selective key restore

To restore a single key from a backed up vault instead of all keys, provide the key name as a key_name argument to the begin_restore method shown above.

Troubleshooting

See the azure-keyvault-administration troubleshooting guide for details on how to diagnose various failure scenarios.

General

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.

Next steps

Several samples are available in the Azure SDK for Python GitHub repository. These samples provide example code for additional Key Vault scenarios:

Additional documentation

For more extensive documentation on Azure Key Vault, see the API reference documentation.

For more extensive documentation on Managed HSM, see the service documentation.

Contributing

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.

Metadata

Release files for azure-keyvault-administration 4.8.0b3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for azure-keyvault-administration 4.8.0b3
File Size Uploaded
azure_keyvault_administration-4.8.0b3.tar.gz 145.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for azure-keyvault-administration 4.8.0b3
File Interpreter ABI Platform
azure_keyvault_administration-4.8.0b3-py3-none-any.whl Python 3 none any Details

Total release size: 285.2 kB

Release files / azure_keyvault_administration-4.8.0b3.tar.gz

Download URL azure_keyvault_administration-4.8.0b3.tar.gz
Size 145.1 kB
Tags Source
SHA-256 checksum
How to use checksums
a45f3c026fc411ac441112c3bb198822e6e03f6cdb53a30a996cfc838f9a5e7d
BLAKE2b-256 checksum
How to use checksums
1a88392cb179f18e85b6f63e3c49e2c0646793e5b9148a6dc8983dc88c225c53
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Release files / azure_keyvault_administration-4.8.0b3-py3-none-any.whl

Download URL azure_keyvault_administration-4.8.0b3-py3-none-any.whl
Size 140.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7f365f4c95231f4e37b234b74c12ff07aa8a40e9556d6133527f8ca5ad09180d
BLAKE2b-256 checksum
How to use checksums
21bcd8fd5a43db6ebab910e28f3d1f5344a53d7f27c92da37e42e830463da6a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page