File: README.md

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (486 lines) | stat: -rw-r--r-- 23,589 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# Azure Key Vault Administration client library for Python

>**Note:** The Administration library only works with [Managed HSM][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](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-keys)) - create, store, and control
access to the keys used to encrypt your data
- Secrets management
([azure-keyvault-secrets](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-secrets)) -
securely store and control access to tokens, passwords, certificates, API keys,
and other secrets
- Certificate management
([azure-keyvault-certificates](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-certificates)) -
create, manage, and deploy public and private SSL/TLS certificates

[Source code][library_src]
| [Package (PyPI)][pypi_package_administration]
| [Package (Conda)](https://anaconda.org/microsoft/azure-keyvault/)
| [API reference documentation][reference_docs]
| [Product documentation][keyvault_docs]
| [Samples][administration_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.8 or later is required to use this package. For more details, please refer to [Azure SDK for Python version support policy](https://github.com/Azure/azure-sdk-for-python/wiki/Azure-SDKs-Python-version-support-policy)._

## Getting started
### Install packages
Install [azure-keyvault-administration][pypi_package_administration] and
[azure-identity][azure_identity_pypi] with [pip][pip]:
```Bash
pip install azure-keyvault-administration azure-identity
```
[azure-identity][azure_identity] is used for Azure Active Directory
authentication as demonstrated below.

### Prerequisites
* An [Azure subscription][azure_sub]
* Python 3.8 or later
* An existing [Key Vault Managed HSM][managed_hsm]. If you need to create one, you can do so using the Azure CLI by following the steps in [this document][managed_hsm_cli].

### Authenticate the client
In order to interact with the Azure Key Vault service, you will need an instance of either a [KeyVaultAccessControlClient](#create-a-keyvaultaccesscontrolclient) or [KeyVaultBackupClient](#create-a-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][default_cred_ref], which is appropriate for most scenarios, including local development and production environments. We recommend using a [managed identity][managed_identity] for authentication in production environments.

See [azure-identity][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][default_cred_ref] 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):

<!-- SNIPPET:access_control_operations.create_an_access_control_client -->

```python
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)
```

<!-- END SNIPPET -->

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

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

<!-- SNIPPET:backup_restore_operations.create_a_backup_restore_client -->

```python
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)
```

<!-- END SNIPPET -->

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][managed_identity_ref] 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][default_cred_ref] 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):

<!-- SNIPPET:settings_operations.create_a_settings_client -->

```python
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)
```

<!-- END SNIPPET -->

> **NOTE:** For an asynchronous client, import `azure.keyvault.administration.aio`'s `KeyVaultSettingsClient` 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.

## Examples
This section contains code snippets covering common tasks:
* Access control
    * [List all role definitions](#list-all-role-definitions)
    * [Set, get, and delete a role definition](#set-get-and-delete-a-role-definition)
    * [List all role assignments](#list-all-role-assignments)
    * [Create, get, and delete a role assignment](#create-get-and-delete-a-role-assignment)
* Backup and restore
    * [Run a pre-backup check](#run-a-pre-backup-check-for-a-collection-of-keys)
    * [Perform a full key backup](#perform-a-full-key-backup)
    * [Run a pre-restore check](#run-a-pre-restore-check-for-a-collection-of-keys)
    * [Perform a full key restore](#perform-a-full-key-restore)
    * [Perform a selective key restore](#perform-a-selective-key-restore)

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

<!-- SNIPPET:access_control_operations.list_role_definitions -->

```python
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}")
```

<!-- END SNIPPET -->

### 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).

<!-- SNIPPET:access_control_operations.create_a_role_definition -->

```python
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)
```

<!-- END SNIPPET -->

<!-- SNIPPET:access_control_operations.update_a_role_definition -->

```python
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
)
```

<!-- END SNIPPET -->

`get_role_definition` can be used by a `KeyVaultAccessControlClient` to fetch a role definition with the specified scope
and unique name.

<!-- SNIPPET:access_control_operations.get_a_role_definition -->

```python
fetched_definition = client.get_role_definition(scope=scope, name=unique_definition_name)
```

<!-- END SNIPPET -->

`delete_role_definition` can be used by a `KeyVaultAccessControlClient` to delete a role definition with the specified
scope and unique name.

<!-- SNIPPET:access_control_operations.delete_a_role_definition -->

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

<!-- END SNIPPET -->

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

<!-- SNIPPET:access_control_operations.list_role_assignments -->

```python
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}")
```

<!-- END SNIPPET -->

### 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](#list-all-role-definitions) for the former,
and an assignment's `principal_id` from the list retrieved in the [above snippet](#list-all-role-assignments) for the
latter. Provide these values, and a scope, to a `KeyVaultAccessControlClient`'s `create_role_assignment` method.

<!-- SNIPPET:access_control_operations.create_a_role_assignment -->

```python
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.")
```

<!-- END SNIPPET -->

`get_role_assignment` can be used by a `KeyVaultAccessControlClient` to fetch an existing role assignment with the
specified scope and unique name.

<!-- SNIPPET:access_control_operations.get_a_role_assignment -->

```python
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.")
```

<!-- END SNIPPET -->

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

<!-- SNIPPET:access_control_operations.delete_a_role_assignment -->

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

<!-- END SNIPPET -->

### 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][managed_identity_backup_setup].

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`][storage_blob], refer
to the library's [credential documentation][sas_docs]. Alternatively, it is possible to
[generate a SAS token in Storage Explorer][storage_explorer].

```python
CONTAINER_URL = os.environ["CONTAINER_URL"]

check_result: KeyVaultBackupOperation = client.begin_pre_backup(CONTAINER_URL, use_managed_identity=True).result()

if check_result.error:
    print(f"Reason the backup cannot be performed: {check_result.error}")
else:
    print("A full key backup can be successfully performed.")
```

Note that the `begin_pre_backup` method returns a poller. Calling `result()` on this poller returns a
`KeyVaultBackupOperation` -- this object will  have a string `error` attribute if the check failed, and otherwise the
check will have succeeded.

### Perform a full key backup
To actually perform the key backup, you can use `KeyVaultBackupClient.begin_backup`.

<!-- SNIPPET:backup_restore_operations.begin_backup -->

```python
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}")
```

<!-- END SNIPPET -->

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](#perform-a-full-key-backup).

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][managed_identity_backup_setup].

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`][storage_blob], refer
to the library's [credential documentation][sas_docs]. Alternatively, it is possible to
[generate a SAS token in Storage Explorer][storage_explorer].

```python
check_result: KeyVaultRestoreOperation = client.begin_pre_restore(
    backup_result.folder_url, use_managed_identity=True
).result()

if check_result.error:
    print(f"Reason the backup cannot be performed: {check_result.error}")
else:
    print("A full key restore can be successfully performed.")
```

Note that the `begin_pre_restore` method returns a poller. Calling `result()` on this poller returns a
`KeyVaultRestoreOperation` -- this object will have a string `error` attribute if the check failed, and otherwise the
`error` will be None if the check succeeded.

### Perform a full key restore
To actually restore your entire collection of keys, you can use `KeyVaultBackupClient.begin_restore`.

<!-- SNIPPET:backup_restore_operations.begin_restore -->

```python
# `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.")
```

<!-- END SNIPPET -->

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](#perform-a-full-key-restore).

## Troubleshooting

See the `azure-keyvault-administration`
[troubleshooting guide](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/TROUBLESHOOTING.md)
for details on how to diagnose various failure scenarios.

### General
Key Vault clients raise exceptions defined in [azure-core][azure_core_exceptions].
For example, if you try to get a role assignment that doesn't exist, KeyVaultAccessControlClient
raises [ResourceNotFoundError](https://aka.ms/azsdk-python-core-exceptions-resource-not-found-error):

```python
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:

- [Create/update/delete role definitions and role assignments][access_control_operations_sample] ([async version][access_control_operations_async_sample])
- [Full backup and restore][backup_operations_sample] ([async version][backup_operations_async_sample])
- [List and update Key Vault settings][settings_operations_sample] ([async version][settings_operations_async_sample])

###  Additional documentation
For more extensive documentation on Azure Key Vault, see the [API reference documentation][reference_docs].

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

## 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][code_of_conduct].
For more information, see the
[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact opencode@microsoft.com with any additional questions or comments.


<!-- LINKS -->
[access_control]: https://learn.microsoft.com/azure/key-vault/managed-hsm/access-control
[access_control_operations_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/access_control_operations.py
[access_control_operations_async_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/access_control_operations_async.py
[administration_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples
[azure_cloud_shell]: https://shell.azure.com/bash
[azure_core_exceptions]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core#azure-core-library-exceptions
[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity
[azure_identity_pypi]: https://pypi.org/project/azure-identity/
[azure_sub]: https://azure.microsoft.com/free/

[backup_operations_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/backup_restore_operations.py
[backup_operations_async_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/backup_restore_operations_async.py
[best_practices]: https://learn.microsoft.com/azure/key-vault/managed-hsm/best-practices
[built_in_roles]: https://learn.microsoft.com/azure/key-vault/managed-hsm/built-in-roles

[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/

[default_cred_ref]: https://aka.ms/azsdk/python/identity/docs#azure.identity.DefaultAzureCredential

[keyvault_docs]: https://learn.microsoft.com/azure/key-vault/

[library_src]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration

[managed_hsm]: https://learn.microsoft.com/azure/key-vault/managed-hsm/overview
[managed_hsm_cli]: https://learn.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli
[managed_identity]: https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview
[managed_identity_backup_setup]: https://learn.microsoft.com/azure/key-vault/managed-hsm/backup-restore#prerequisites-if-backing-up-and-restoring-using-user-assigned-managed-identity
[managed_identity_ref]: https://aka.ms/azsdk/python/identity/docs#azure.identity.ManagedIdentityCredential

[pip]: https://pypi.org/project/pip/
[pypi_package_administration]: https://pypi.org/project/azure-keyvault-administration

[reference_docs]: https://aka.ms/azsdk/python/keyvault-administration/docs

[sas_docs]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob/README.md#types-of-credentials
[settings_operations_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/settings_operations.py
[settings_operations_async_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/settings_operations_async.py
[storage_blob]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/storage/azure-storage-blob/README.md
[storage_explorer]: https://learn.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer