如何使用Azure Python SDK为Azure订阅用户分配Reader角色?
如何使用Azure Python SDK分配Reader角色
问题描述
我需要用Azure Python SDK给Azure订阅/资源组下的用户分配Reader角色,目前已经能用requests直接调用REST API实现,但不知道怎么用SDK完成同样的操作,现有REST API代码如下:
import requests import uuid scope = "subscriptions/{subscription_id}/resourceGroups/{resource_group_name}" role_assignment_id = str(uuid.uuid4()) role_definition_id = "/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7" # Reader role ID principal_id = "{user_principal_id}" url = f"https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{role_assignment_id}?api-version=2022-04-01" access_token = "{access_token}" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } body = { "properties": { "roleDefinitionId": role_definition_id, "principalId": principal_id } } response = requests.put(url, headers=headers, json=body) if response.status_code == 201: print("Role assigned successfully.") else: print(f"Failed to assign role. Status Code: {response.status_code}, Response: {response.text}")
解决方案
使用Azure Python SDK的azure-mgmt-authorization包可以直接实现角色分配,步骤如下:
1. 安装依赖包
执行以下命令安装所需SDK包:
pip install azure-mgmt-authorization azure-identity
2. 完整SDK实现代码
from azure.identity import DefaultAzureCredential from azure.mgmt.authorization import AuthorizationManagementClient import uuid # 替换为你的订阅ID、资源组名称、用户主体ID SUBSCRIPTION_ID = "{subscription_id}" RESOURCE_GROUP_NAME = "{resource_group_name}" PRINCIPAL_ID = "{user_principal_id}" # Reader角色的固定ID READER_ROLE_ID = "acdd72a7-3385-48ef-bd42-f606fba81ae7" # 构建权限范围(可以是订阅、资源组或资源级别) scope = f"subscriptions/{SUBSCRIPTION_ID}/resourceGroups/{RESOURCE_GROUP_NAME}" # 使用DefaultAzureCredential进行认证(支持本地开发、Azure托管环境等多种认证方式) credential = DefaultAzureCredential() auth_client = AuthorizationManagementClient(credential, SUBSCRIPTION_ID) # 生成唯一的角色分配ID role_assignment_id = str(uuid.uuid4()) # 创建角色分配 try: role_assignment = auth_client.role_assignments.create( scope=scope, role_assignment_name=role_assignment_id, parameters={ "role_definition_id": f"/subscriptions/{SUBSCRIPTION_ID}/providers/Microsoft.Authorization/roleDefinitions/{READER_ROLE_ID}", "principal_id": PRINCIPAL_ID } ) print("Role assigned successfully.") print(f"Role assignment ID: {role_assignment.id}") except Exception as e: print(f"Failed to assign role: {str(e)}")
代码说明
- 认证方式:使用
DefaultAzureCredential自动适配不同环境的认证(本地用Azure CLI、VS Code等,Azure服务用托管标识),无需手动获取access token。 - 角色分配范围:示例中使用资源组级别,若要给整个订阅分配,将
scope改为f"subscriptions/{SUBSCRIPTION_ID}"即可。 - 角色定义ID:Reader角色的ID是固定值
acdd72a7-3385-48ef-bd42-f606fba81ae7,可通过auth_client.role_definitions.list()查询所有内置角色ID。
内容的提问来源于stack exchange,提问作者James Wilton
相关产品推荐
相关产品推荐

