如何通过Azure Resource Graph API获取指定资源的角色分配?
使用Azure Resource Graph API查询特定资源的角色分配
方法一:通过Azure Resource Graph实现
Azure Resource Graph支持查询Microsoft.Authorization/roleAssignments类型的资源,你可以用Kusto查询语句筛选指定资源ID的角色分配,示例如下:
authorizationresources | where type == "microsoft.authorization/roleassignments" | where properties.scope == "/subscriptions/xxx/resourceGroups/xxx/providers/xxx/xxx/your-resource-id" | extend roleDefinitionId = split(properties.roleDefinitionId, '/')[-1] | join kind=leftouter ( authorizationresources | where type == "microsoft.authorization/roledefinitions" | project roleDefinitionId = id, roleName = properties.roleName ) on roleDefinitionId | project 角色分配ID = id, 角色名称 = roleName, 主体ID = properties.principalId, 主体类型 = properties.principalType, 作用域 = properties.scope
关键说明:
- 把
properties.scope的值替换为目标资源的完整ID(比如虚拟机的完整ID格式为/subscriptions/订阅ID/resourceGroups/资源组名/providers/Microsoft.Compute/virtualMachines/虚拟机名) - 通过关联
roledefinitions表,可将角色定义ID转换为“所有者”“参与者”这类可读名称 - 可根据需求调整
project后的字段,增删需要展示的信息
方法二:使用Azure管理API(Resource Management API)
如果Resource Graph的查询无法满足更精细的实时需求,也可以直接调用Azure管理API:
- 请求地址:
GET {resource-id}/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01,替换{resource-id}为目标资源的完整ID - 也可用Azure CLI快速测试,命令如下:
az role assignment list --scope "/subscriptions/xxx/resourceGroups/xxx/providers/xxx/xxx/your-resource-id"
注意事项
- 无论用哪种方式,当前账号都需要具备读取角色分配的权限(比如“读者”或更高权限)
- Resource Graph查询结果存在几分钟延迟,需实时数据建议用管理API
内容的提问来源于stack exchange,提问作者Azgu
相关产品推荐
相关产品推荐

