Skip to content

Commit d1d8e9f

Browse files
authored
[Key Vault] Add azure-keyvault-administration samples (Azure#19736)
1 parent 52ae26d commit d1d8e9f

File tree

7 files changed

+366
-4
lines changed

7 files changed

+366
-4
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
page_type: sample
3+
languages:
4+
- python
5+
products:
6+
- azure
7+
- azure-key-vault
8+
urlFragment: keyvault-administration-samples
9+
---
10+
11+
# Azure Key Vault Administration Client Library Python Samples
12+
13+
## Prerequisites
14+
15+
You must have an [Azure subscription](https://azure.microsoft.com/free) and an
16+
[Azure Managed HSM](https://docs.microsoft.com/azure/key-vault/managed-hsm/) to run
17+
these samples. You can create a managed HSM with the
18+
[Azure CLI](https://docs.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli).
19+
20+
## Setup
21+
22+
To run these samples, first install the Key Vault Administration and Azure Identity libraries:
23+
24+
```commandline
25+
pip install azure-keyvault-administration azure-identity
26+
```
27+
28+
[Azure Identity](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md) is used for authenticating Key Vault clients. These samples use the
29+
[DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md#defaultazurecredential), but any credential from the library can be used with Key Vault clients.
30+
31+
## Contents
32+
| File | Description |
33+
|-------------|-------------|
34+
| [access_control_operations.py][access_control_operations_sample] | create/update/delete role definitions and role assignments |
35+
| [access_control_operations_async.py][access_control_operations_async_sample] | create/update/delete role definitions and role assignments with an async client |
36+
| [backup_restore_operations.py][backup_operations_sample] | full backup and restore |
37+
| [backup_restore_operations_async.py][backup_operations_async_sample] | full backup and restore with an async client |
38+
39+
[access_control_operations_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/access_control_operations.py
40+
[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
41+
[backup_operations_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration/samples/backup_restore_operations.py
42+
[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
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# ------------------------------------
2+
# Copyright (c) Microsoft Corporation.
3+
# Licensed under the MIT License.
4+
# ------------------------------------
5+
import os
6+
7+
from azure.keyvault.administration import (
8+
KeyVaultAccessControlClient,
9+
KeyVaultDataAction,
10+
KeyVaultPermission,
11+
KeyVaultRoleScope,
12+
)
13+
from azure.identity import DefaultAzureCredential
14+
15+
# ----------------------------------------------------------------------------------------------------------
16+
# Prerequisites:
17+
# 1. A managed HSM (https://docs.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli)
18+
#
19+
# 2. azure-keyvault-administration and azure-identity libraries (pip install these)
20+
#
21+
# 3. Set environment variable MANAGED_HSM_URL with the URL of your managed HSM
22+
#
23+
# 4. Set up your environment to use azure-identity's DefaultAzureCredential. To authenticate a service principal with
24+
# environment variables, set AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID
25+
# (See https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration#authenticate-the-client)
26+
#
27+
# ----------------------------------------------------------------------------------------------------------
28+
# Sample - demonstrates role definition and assignment operations for Managed HSM
29+
#
30+
# 1. Create a role definition (set_role_definition)
31+
#
32+
# 2. Update a role definition (set_role_definition)
33+
#
34+
# 3. Create a role assignment (create_role_assignment)
35+
#
36+
# 4. Delete a role assignment (delete_role_assignment)
37+
#
38+
# 5. Delete a role definition (delete_role_definition)
39+
# ----------------------------------------------------------------------------------------------------------
40+
41+
MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
42+
43+
# Instantiate an access control client that will be used to call the service.
44+
# Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
45+
credential = DefaultAzureCredential()
46+
client = KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL, credential=credential)
47+
48+
# Let's first create a custom role definition. This role permits creating keys in a Managed HSM.
49+
# We'll provide a friendly role name, and let a unique role definition name (a GUID) be generated for us.
50+
print("\n.. Create a role definition")
51+
role_name = "customRole"
52+
scope = KeyVaultRoleScope.GLOBAL
53+
permissions = [KeyVaultPermission(data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]
54+
role_definition = client.set_role_definition(scope=scope, role_name=role_name, permissions=permissions)
55+
print("Role definition '{}' created successfully.".format(role_definition.role_name))
56+
57+
# Let's update our role definition to allow reading keys, but not allow creating keys.
58+
# To update an existing definition, pass the name keyword argument to set_role_definition. This is the unique name
59+
# of the role definition, which is stored in KeyVaultRoleDefinition.name.
60+
print("\n.. Update a role definition")
61+
new_permissions = [
62+
KeyVaultPermission(
63+
data_actions=[KeyVaultDataAction.READ_HSM_KEY],
64+
not_data_actions=[KeyVaultDataAction.CREATE_HSM_KEY]
65+
)
66+
]
67+
unique_definition_name = role_definition.name
68+
updated_definition = client.set_role_definition(
69+
scope=scope, name=unique_definition_name, role_name=role_name, permissions=new_permissions
70+
)
71+
print("Role definition '{}' updated successfully.".format(updated_definition.role_name))
72+
73+
# Now let's create a role assignment to apply our role definition to our service principal.
74+
# Since we don't provide the name keyword argument to create_role_definition, a unique role assignment name (a GUID)
75+
# is generated for us.
76+
print("\n.. Create a role assignment")
77+
principal_id = os.environ["AZURE_CLIENT_ID"]
78+
definition_id = updated_definition.id
79+
role_assignment = client.create_role_assignment(scope=scope, definition_id=definition_id, principal_id=principal_id)
80+
print("Role assignment created successfully.")
81+
82+
# Let's delete the role assignment.
83+
print("\n.. Delete a role assignment")
84+
client.delete_role_assignment(scope=scope, name=role_assignment.name)
85+
print("Role assignment deleted successfully.")
86+
87+
# Finally, let's delete the role definiton as well.
88+
print("\n.. Delete a role definition")
89+
client.delete_role_definition(scope=scope, name=definition_id)
90+
print("Role definition deleted successfully.")
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# ------------------------------------
2+
# Copyright (c) Microsoft Corporation.
3+
# Licensed under the MIT License.
4+
# ------------------------------------
5+
import asyncio
6+
import os
7+
8+
from azure.keyvault.administration import KeyVaultDataAction, KeyVaultPermission, KeyVaultRoleScope
9+
from azure.keyvault.administration.aio import KeyVaultAccessControlClient
10+
from azure.identity.aio import DefaultAzureCredential
11+
12+
# ----------------------------------------------------------------------------------------------------------
13+
# Prerequisites:
14+
# 1. A managed HSM (https://docs.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli)
15+
#
16+
# 2. azure-keyvault-administration and azure-identity libraries (pip install these)
17+
#
18+
# 3. Set environment variable MANAGED_HSM_URL with the URL of your managed HSM
19+
#
20+
# 4. Set up your environment to use azure-identity's DefaultAzureCredential. To authenticate a service principal with
21+
# environment variables, set AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID
22+
# (See https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration#authenticate-the-client)
23+
#
24+
# ----------------------------------------------------------------------------------------------------------
25+
# Sample - demonstrates role definition and assignment operations for Managed HSM
26+
#
27+
# 1. Create a role definition (set_role_definition)
28+
#
29+
# 2. Update a role definition (set_role_definition)
30+
#
31+
# 3. Create a role assignment (create_role_assignment)
32+
#
33+
# 4. Delete a role assignment (delete_role_assignment)
34+
#
35+
# 5. Delete a role definition (delete_role_definition)
36+
# ----------------------------------------------------------------------------------------------------------
37+
38+
async def run_sample():
39+
MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
40+
41+
# Instantiate an access control client that will be used to call the service.
42+
# Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
43+
credential = DefaultAzureCredential()
44+
client = KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL, credential=credential)
45+
46+
# Let's first create a custom role definition. This role permits creating keys in a Managed HSM.
47+
# We'll provide a friendly role name, and let a unique role definition name (a GUID) be generated for us.
48+
print("\n.. Create a role definition")
49+
role_name = "customRole"
50+
scope = KeyVaultRoleScope.GLOBAL
51+
permissions = [KeyVaultPermission(data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]
52+
role_definition = await client.set_role_definition(scope=scope, role_name=role_name, permissions=permissions)
53+
print("Role definition '{}' created successfully.".format(role_definition.role_name))
54+
55+
# Let's update our role definition to allow reading keys, but not allow creating keys.
56+
# To update an existing definition, pass the name keyword argument to set_role_definition. This is the unique
57+
# name of the role definition, which is stored in KeyVaultRoleDefinition.name.
58+
print("\n.. Update a role definition")
59+
new_permissions = [
60+
KeyVaultPermission(
61+
data_actions=[KeyVaultDataAction.READ_HSM_KEY],
62+
not_data_actions=[KeyVaultDataAction.CREATE_HSM_KEY]
63+
)
64+
]
65+
unique_definition_name = role_definition.name
66+
updated_definition = await client.set_role_definition(
67+
scope=scope, name=unique_definition_name, role_name=role_name, permissions=new_permissions
68+
)
69+
print("Role definition '{}' updated successfully.".format(updated_definition.role_name))
70+
71+
# Now let's create a role assignment to apply our role definition to our service principal.
72+
# Since we don't provide the name keyword argument to create_role_definition, a unique role assignment name
73+
# (a GUID) is generated for us.
74+
print("\n.. Create a role assignment")
75+
principal_id = os.environ["AZURE_CLIENT_ID"]
76+
definition_id = updated_definition.id
77+
role_assignment = await client.create_role_assignment(
78+
scope=scope, definition_id=definition_id, principal_id=principal_id
79+
)
80+
print("Role assignment created successfully.")
81+
82+
# Let's delete the role assignment.
83+
print("\n.. Delete a role assignment")
84+
await client.delete_role_assignment(scope=scope, name=role_assignment.name)
85+
print("Role assignment deleted successfully.")
86+
87+
# Finally, let's delete the role definiton as well.
88+
print("\n.. Delete a role definition")
89+
await client.delete_role_definition(scope=scope, name=definition_id)
90+
print("Role definition deleted successfully.")
91+
92+
await credential.close()
93+
await client.close()
94+
95+
96+
if __name__ == "__main__":
97+
loop = asyncio.get_event_loop()
98+
loop.run_until_complete(run_sample())
99+
loop.close()
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# ------------------------------------
2+
# Copyright (c) Microsoft Corporation.
3+
# Licensed under the MIT License.
4+
# ------------------------------------
5+
import os
6+
7+
from azure.keyvault.administration import KeyVaultBackupClient
8+
from azure.identity import DefaultAzureCredential
9+
10+
# ----------------------------------------------------------------------------------------------------------
11+
# Prerequisites:
12+
# 1. A managed HSM (https://docs.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli)
13+
#
14+
# 2. azure-keyvault-administration and azure-identity libraries (pip install these)
15+
#
16+
# 3. Set environment variable MANAGED_HSM_URL with the URL of your managed HSM
17+
#
18+
# 4. Set up your environment to use azure-identity's DefaultAzureCredential. To authenticate a service principal with
19+
# environment variables, set AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID
20+
# (See https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration#authenticate-the-client)
21+
#
22+
# 5. A storage account containing a blob storage container
23+
# (See https://docs.microsoft.com/azure/storage/blobs/storage-blobs-introduction)
24+
#
25+
# 6. Set environment variables CONTAINER_URL and SAS_TOKEN corresponding to your blob container's URI and SAS
26+
# (See https://docs.microsoft.com/azure/storage/common/storage-sas-overview)
27+
#
28+
# For more details, see https://docs.microsoft.com/azure/key-vault/managed-hsm/backup-restore
29+
#
30+
# ----------------------------------------------------------------------------------------------------------
31+
# Sample - demonstrates full backup and restore operations for Managed HSM
32+
#
33+
# 1. Perform a full backup (begin_backup)
34+
#
35+
# 2. Perform a full restore (begin_restore)
36+
# ----------------------------------------------------------------------------------------------------------
37+
38+
MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
39+
CONTAINER_URL = os.environ["CONTAINER_URL"]
40+
SAS_TOKEN = os.environ["SAS_TOKEN"]
41+
42+
# Instantiate a backup client that will be used to call the service.
43+
# Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
44+
credential = DefaultAzureCredential()
45+
client = KeyVaultBackupClient(vault_url=MANAGED_HSM_URL, credential=credential)
46+
47+
# Let's back up the vault with begin_backup, which returns a poller. Calling result() on the poller will return a
48+
# KeyVaultBackupResult that contains the URL of the backup after the operation completes. Calling wait() on the
49+
# poller will wait until the operation is complete.
50+
print("\n.. Back up the vault")
51+
backup_result = client.begin_backup(CONTAINER_URL, SAS_TOKEN).result()
52+
print("Vault backed up successfully.")
53+
54+
# Now let's the vault by calling begin_restore, which also returns a poller. Calling result() on the poller will
55+
# return None after the operation completes. Calling wait() on the poller will wait until the operation is complete.
56+
# To restore a single key from the backed up vault instead, pass the key_name keyword argument.
57+
print("\n.. Restore the full vault")
58+
client.begin_restore(backup_result.folder_url, SAS_TOKEN).wait()
59+
print("Vault restored successfully.")
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# ------------------------------------
2+
# Copyright (c) Microsoft Corporation.
3+
# Licensed under the MIT License.
4+
# ------------------------------------
5+
import asyncio
6+
import os
7+
8+
from azure.keyvault.administration.aio import KeyVaultBackupClient
9+
from azure.identity.aio import DefaultAzureCredential
10+
11+
# ----------------------------------------------------------------------------------------------------------
12+
# Prerequisites:
13+
# 1. A managed HSM (https://docs.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli)
14+
#
15+
# 2. azure-keyvault-administration and azure-identity libraries (pip install these)
16+
#
17+
# 3. Set environment variable MANAGED_HSM_URL with the URL of your managed HSM
18+
#
19+
# 4. Set up your environment to use azure-identity's DefaultAzureCredential. To authenticate a service principal with
20+
# environment variables, set AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID
21+
# (See https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration#authenticate-the-client)
22+
#
23+
# 5. A storage account containing a blob storage container
24+
# (See https://docs.microsoft.com/azure/storage/blobs/storage-blobs-introduction)
25+
#
26+
# 6. Set environment variables CONTAINER_URL and SAS_TOKEN corresponding to your blob container's URI and SAS
27+
# (See https://docs.microsoft.com/azure/storage/common/storage-sas-overview)
28+
#
29+
# For more details, see https://docs.microsoft.com/azure/key-vault/managed-hsm/backup-restore
30+
#
31+
# ----------------------------------------------------------------------------------------------------------
32+
# Sample - demonstrates full backup and restore operations for Managed HSM
33+
#
34+
# 1. Perform a full backup (begin_backup)
35+
#
36+
# 2. Perform a full restore (begin_restore)
37+
# ----------------------------------------------------------------------------------------------------------
38+
39+
async def run_sample():
40+
MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]
41+
CONTAINER_URL = os.environ["CONTAINER_URL"]
42+
SAS_TOKEN = os.environ["SAS_TOKEN"]
43+
44+
# Instantiate a backup client that will be used to call the service.
45+
# Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
46+
credential = DefaultAzureCredential()
47+
client = KeyVaultBackupClient(vault_url=MANAGED_HSM_URL, credential=credential)
48+
49+
# Let's back up the vault with begin_backup, which returns a poller. Calling result() on the poller will return
50+
# a KeyVaultBackupResult that contains the URL of the backup after the operation completes. Calling wait() on
51+
# the poller will wait until the operation is complete.
52+
print("\n.. Back up the vault")
53+
backup_poller = await client.begin_backup(CONTAINER_URL, SAS_TOKEN)
54+
backup_result = await backup_poller.result()
55+
print("Vault backed up successfully.")
56+
57+
# Now let's the vault by calling begin_restore, which also returns a poller. Calling result() on the poller will
58+
# return None after the operation completes. Calling wait() on the poller will wait until the operation is
59+
# complete. To restore a single key from the backed up vault instead, pass the key_name keyword argument.
60+
print("\n.. Restore the full vault")
61+
restore_poller = await client.begin_restore(backup_result.folder_url, SAS_TOKEN)
62+
await restore_poller.wait()
63+
print("Vault restored successfully.")
64+
65+
await credential.close()
66+
await client.close()
67+
68+
69+
if __name__ == "__main__":
70+
loop = asyncio.get_event_loop()
71+
loop.run_until_complete(run_sample())
72+
loop.close()

sdk/keyvault/azure-keyvault-administration/tests/test_examples_administration.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def test_example_backup_and_restore(self, container_uri, sas_token):
6666
restore_poller = backup_client.begin_restore(folder_url, sas_token)
6767

6868
# check if the restore completed
69-
done = backup_poller.done()
69+
done = restore_poller.done()
7070

7171
# wait for the restore to complete
7272
restore_poller.wait()
@@ -91,7 +91,7 @@ def test_example_selective_key_restore(self, container_uri, sas_token):
9191
restore_poller = backup_client.begin_restore(folder_url, sas_token, key_name=key_name)
9292

9393
# check if the restore completed
94-
done = backup_poller.done()
94+
done = restore_poller.done()
9595

9696
# wait for the restore to complete
9797
restore_poller.wait()

0 commit comments

Comments
 (0)