Search code examples
azureazure-pipelinesmicrosoft-entra-id

Add PIM role assignment with PowerShell - Access issue


I want to create an Azure DevOps pipeline that creates role assignments to Groups, Resources and AD.

In the script that is executed by the pipeline I try to run the following command:

Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId 'AzureResources' -ResourceId "$resourceID" -RoleDefinitionId "$roleId" -SubjectId "$userId" -AssignmentState "$AssignmentType" -Schedule $schedule -Reason "Test PIM Automation"

All the properties are correct but I still get the following error.

##[error]Error occurred while executing OpenAzureADMSPrivilegedRoleAssignmentRequest 
Code: UnauthorizedAccessException
Message: Attempted to perform an unauthorized operation.
InnerError:
  RequestId: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX
  DateTimeStamp: Tue, 12 Mar 2024 07:42:00 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed

The service connection that the pipeline uses has Owner role in the Subscription that the resource exists

I want to execute this also for ProviderId = 'aadGroups'. Please tell me what kind of access should I have.


Solution

  • A solution to this issue finally found. The AzureAD Preview PowerShell module is deprecated since March 2024 and will be end of support on March 2025. So Microsoft recommends to use Microsoft.Graph PowerShell module for Group assignments and Entra ID role assignments with PIM. For Azure Resources role assignments the Az.Resources PowerShell module can be used.

    Here is an example of Eligible PIM role assignment for Azure Group membership:

    $params = @{
      accessId = "member"
      principalId = "$userId"
      groupId = "$groupId"
      action = "AdminAssign"
      scheduleInfo = @{
        startDateTime = $currentDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
        expiration = @{
          type = "afterDateTime"
          duration = "PT8H"
          endDateTime = $expirationDateTime
        }
      }
      justification = "${{parameters.Reason}}"
    }
    
    New-MgIdentityGovernancePrivilegedAccessGroupEligibilityScheduleRequest -BodyParameter $params
    

    Here is an example of Eligible PIM role assignment for RBAC role in Azure Resources:

    $guid = New-Guid
    $rg = Get-AzResourceGroup -Name $rgName
    $scope = $rg.ResourceId
    New-AzRoleEligibilityScheduleRequest -Name $guid -Scope $scope -ExpirationDuration PT8H -ExpirationType AfterDateTime -ExpirationEndDateTime $expirationDateTime -ScheduleInfoStartDateTime $startDateTime -PrincipalId $principalId -RequestType AdminAssign -RoleDefinitionId /subscriptions/${{parameters.SubId}}/providers/Microsoft.Authorization/roleDefinitions/$RBACRoleId
    

    Documentation: