如何通过PowerShell/REST API自动化激活Azure资源PIM角色(含管理组级)?
管理组级别Azure资源PIM角色自动化激活方案
PowerShell(Microsoft Graph模块)示例
前置准备
- 安装Microsoft Graph PowerShell模块:
Install-Module Microsoft.Graph -Force - 确保账号拥有
RoleManagement.ReadWrite.AzureResources权限,且权限覆盖目标管理组 - 提前获取:管理组ID、目标用户ID、对应角色的定义ID(比如Contributor的角色ID)
操作步骤
- 连接Graph并指定所需权限
Connect-MgGraph -Scopes "RoleManagement.ReadWrite.AzureResources"
- 查询用户在该管理组下的可激活角色实例
$mgmtGroupId = "你的管理组ID" $targetUserId = "要激活角色的用户ID" $roleDefId = "管理组角色的定义ID" # 筛选用户在目标管理组下的Eligible角色实例 $roleInstance = Get-MgRoleManagementDirectoryRoleAssignmentScheduleInstance -Filter "principalId eq '$targetUserId' and roleDefinitionId eq '$roleDefId' and directoryScopeId eq '/managementGroups/$mgmtGroupId'"
- 提交激活请求
$activationParams = @{ scheduleInfo = @{ startDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") expiration = @{ type = "afterDuration" duration = "PT8H" # 激活时长,示例为8小时,可按需调整 } } justification = "自动化运维操作需要激活管理组角色" } New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $activationParams -ScheduleInstanceId $roleInstance.Id
REST API示例
请求端点
POST https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleRequests
请求头
Authorization: Bearer {你的访问令牌} Content-Type: application/json
请求体
{ "action": "activate", "justification": "自动化运维操作需要激活管理组角色", "scheduleInfo": { "startDateTime": "2024-05-20T09:00:00Z", "expiration": { "type": "afterDuration", "duration": "PT8H" } }, "principalId": "{目标用户ID}", "roleDefinitionId": "{管理组角色定义ID}", "directoryScopeId": "/managementGroups/{你的管理组ID}" }
关键注意事项
- 目录范围必须正确:管理组的
directoryScopeId格式固定为/managementGroups/{管理组ID},不要误用订阅ID或其他路径 - 权限验证:自动化账号的权限必须覆盖目标管理组,否则会出现权限不足的错误
- 角色实例确认:确保用户确实拥有该管理组角色的Eligible资格,否则无法查询到对应实例
- 区分资源与AAD PIM:Azure资源PIM的操作依托于
roleManagement/directory下的资源角色管理端点,不要和AAD角色的操作混淆
内容的提问来源于stack exchange,提问作者shadowz1337
相关产品推荐
相关产品推荐

