File: access_control_operations_async.py

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 (98 lines) | stat: -rw-r--r-- 4,649 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
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import asyncio
import os

from azure.keyvault.administration import KeyVaultDataAction, KeyVaultPermission, KeyVaultRoleScope
from azure.keyvault.administration.aio import KeyVaultAccessControlClient
from azure.identity.aio import DefaultAzureCredential

# ----------------------------------------------------------------------------------------------------------
# Prerequisites:
# 1. A managed HSM (https://learn.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli)
#
# 2. azure-keyvault-administration and azure-identity libraries (pip install these)
#
# 3. Set environment variable MANAGED_HSM_URL with the URL of your managed HSM
#    
# 4. Set up your environment to use azure-identity's DefaultAzureCredential. For more information about how to configure
#    the DefaultAzureCredential, refer to https://aka.ms/azsdk/python/identity/docs#azure.identity.DefaultAzureCredential
#
# ----------------------------------------------------------------------------------------------------------
# Sample - demonstrates role definition and assignment operations for Managed HSM
#
# 1. Create a role definition (set_role_definition)
#
# 2. Update a role definition (set_role_definition)
#
# 3. Create a role assignment (create_role_assignment)
#
# 4. Delete a role assignment (delete_role_assignment)
#
# 5. Delete a role definition (delete_role_definition)
# ----------------------------------------------------------------------------------------------------------

async def run_sample():
    MANAGED_HSM_URL = os.environ["MANAGED_HSM_URL"]

    # Instantiate an access control client that will be used to call the service.
    # Here we use the DefaultAzureCredential, but any azure-identity credential can be used.
    credential = DefaultAzureCredential()
    client = KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL, credential=credential)
    
    # Let's first create a custom role definition. This role permits creating keys in a Managed HSM.
    # We'll provide a friendly role name, and let a unique role definition name (a GUID) be generated for us.
    print("\n.. Create a role definition")
    role_name = "customRole"
    scope = KeyVaultRoleScope.GLOBAL
    permissions = [KeyVaultPermission(data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]
    role_definition = await client.set_role_definition(scope=scope, role_name=role_name, permissions=permissions)
    print(f"Role definition '{role_definition.role_name}' created successfully.")

    # Let's update our role definition to allow reading keys, but not allow creating keys.
    # To update an existing definition, pass the name keyword argument to set_role_definition. This is the unique
    # name of the role definition, which is stored in KeyVaultRoleDefinition.name.
    print("\n.. Update a role definition")
    new_permissions = [
        KeyVaultPermission(
            data_actions=[KeyVaultDataAction.READ_HSM_KEY],
            not_data_actions=[KeyVaultDataAction.CREATE_HSM_KEY]
        )
    ]
    unique_definition_name = role_definition.name
    updated_definition = await client.set_role_definition(
        scope=scope, name=unique_definition_name, role_name=role_name, permissions=new_permissions
    )
    print(f"Role definition '{updated_definition.role_name}' updated successfully.")

    # Now let's create a role assignment to apply our role definition to our service principal.
    # Since we don't provide the name keyword argument to create_role_definition, a unique role assignment name
    # (a GUID) is generated for us.
    print("\n.. Create a role assignment")
    principal_id = os.environ["AZURE_CLIENT_ID"]
    definition_id = updated_definition.id
    assert definition_id
    role_assignment = await client.create_role_assignment(
        scope=scope, definition_id=definition_id, principal_id=principal_id
    )
    assert role_assignment.name
    print(f"Role assignment {role_assignment.name} created successfully.")

    # Let's delete the role assignment.
    print("\n.. Delete a role assignment")
    await client.delete_role_assignment(scope=scope, name=role_assignment.name)
    print("Role assignment deleted successfully.")

    # Finally, let's delete the role definition as well.
    print("\n.. Delete a role definition")
    await client.delete_role_definition(scope=scope, name=definition_id)
    print("Role definition deleted successfully.")

    await credential.close()
    await client.close()


if __name__ == "__main__":
    asyncio.run(run_sample())