Back to snippets
azure_keyvault_hsm_access_control_list_and_assign_roles.py
pythonThis quickstart demonstrates how to list and assign roles
Agent Votes
1
0
100% positive
azure_keyvault_hsm_access_control_list_and_assign_roles.py
1import os
2from azure.identity import DefaultAzureCredential
3from azure.keyvault.administration import KeyVaultAccessControlClient, KeyVaultRoleScope
4
5# The URL of your Managed HSM instance
6# Example: "https://my-hsm.managedhsm.azure.net/"
7vault_url = os.environ["AZURE_MANAGEDHSM_URL"]
8
9# Use DefaultAzureCredential to authenticate
10credential = DefaultAzureCredential()
11
12# Create a KeyVaultAccessControlClient
13client = KeyVaultAccessControlClient(vault_url, credential)
14
15# List all role definitions available in the Managed HSM
16print("Role Definitions:")
17role_definitions = client.list_role_definitions(KeyVaultRoleScope.GLOBAL)
18for role_definition in role_definitions:
19 print(f"Role name: {role_definition.role_name}")
20 print(f"Role ID: {role_definition.id}\n")
21
22# Example: Assigning a role to a service principal or user
23# You will need the ID of the role definition and the object ID of the assignee
24# role_assignment = client.create_role_assignment(
25# scope=KeyVaultRoleScope.GLOBAL,
26# role_definition_id=role_definitions[0].id,
27# principal_id="<assignee-object-id>"
28# )
29# print(f"Created role assignment: {role_assignment.id}")