How do you automate PIM for Groups? (Part 3. Expiration time, Policies, and experiments)
Tags: powershell, microsoftgraph, entraid, pim
Published: 2024-04-24 19:53:24

That is the last part of the posts related to 'PIM for Groups' technology.

The links are here:

* [Let's talk about PIM](https://dev.to/rokicool/lets-talk-about-pim-42lo)
* [How do you automate PIM for Groups? (Part 1 - Setup)](https://dev.to/rokicool/how-do-you-automate-pim-for-groups-part-1-setup-pl5)
* [How do you automate PIM for Groups? (Part 2. Playing with PIM for Groups via API)](https://dev.to/rokicool/how-do-you-automate-pim-for-groups-part-2-playing-with-pim-for-groups-via-api-lli)


I am far from proclaiming that these posts cover the entire technology and API. However, my access to the Trial P2 Entra ID license is going to expire, so I need to put the final dot or exclamation mark. 

## Let us have a look at the expiration 

Both 'the PIM eligibility assignment' and 'the activation of the PIM eligibility assignment' have an expiration time. 

Let's talk about the 'PIM eligibility assignment expiration.'

### How do you get the PIM eligibility expiration time?

Assume that you need to know when the users' PIM eligibility expires. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e5csg54qzfjl049rvu7w.png)

To access that information, you should make a call to [List eligibilitySchedules](https://learn.microsoft.com/en-us/graph/api/privilegedaccessgroup-list-eligibilityschedules?view=graph-rest-1.0&tabs=powershell) API using PowerShell function with the ridiculously long name: [Get-MgIdentityGovernancePrivilegedAccessGroupEligibilitySchedule](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.identity.governance/get-mgidentitygovernanceprivilegedaccessgroupeligibilityschedule?view=graph-powershell-1.0)

Here is an example:

``` PowerShell
pwsh> $ea = Get-MgIdentityGovernancePrivilegedAccessGroupEligibilitySchedule -Filter ("groupId eq '{0}' and principalId eq '{1}'" -f $($pg01.Id), $($u01.Id))
pwsh> $ea.ScheduleInfo.Expiration.EndDateTime

Sunday, April 28, 2024 10:38:29 PM

```

The difference between Portal and PowerShell results is 5 hours. It's probably because PowerShell returns Greenwich time, but Portal shows my local (Central Time). 

### How do we extend PIM eligibility assignment expiration time?

What if we understand that the expiration time of the PIM eligibility assignment must be postponed? 

The answer is... the same [Create eligibilityScheduleRequest](https://learn.microsoft.com/en-us/graph/api/privilegedaccessgroup-post-eligibilityschedulerequests?view=graph-rest-1.0&tabs=powershell) via PowerShell [New-MgIdentityGovernancePrivilegedAccessGroupEligibilityScheduleRequest](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.identity.governance/new-mgidentitygovernanceprivilegedaccessgroupeligibilityschedulerequest?view=graph-powershell-1.0)

``` PowerShell 
pwsh> $params = @{
	accessId = "member"
	principalId = "$($u01.Id)"
	groupId = "$($pg01.Id)"
	action = "adminExtend"
	scheduleInfo = @{
		startDateTime = $(Get-Date)
		expiration = @{
			type = "AfterDateTime"
			endDateTime = $((Get-date).AddDays(14))
		}
	}
	justification = "Expire the PIM eligibility in two weeks."
}

pwsh> New-MgIdentityGovernancePrivilegedAccessGroupEligibilityScheduleRequest -BodyParameter $params

Action      ApprovalId CompletedDateTime     CreatedDateTime       CustomData Id                                   IsValidationOnly Justification                            Status      AccessId GroupId                              Princip
                                                                                                                                                                                                                                       alId
------      ---------- -----------------     ---------------       ---------- --                                   ---------------- -------------                            ------      -------- -------                              -------
adminExtend            4/21/2024 11:11:08 PM 4/21/2024 11:11:07 PM            0d44080f-8c56-41c1-a2ee-730eeff3e397 False            Expire the PIM eligibility in two weeks. Provisioned member   853d7402-51b4-4cd4-9b8d-9f159311859d c88163…

pwsh> 
pwsh> $ea = Get-MgIdentityGovernancePrivilegedAccessGroupEligibilitySchedule -Filter ("groupId eq '{0}' and principalId eq '{1}'" -f $($pg01.Id), $($u01.Id))
pwsh> 
pwsh> $ea.ScheduleInfo.Expiration.EndDateTime

Sunday, May 5, 2024 11:11:06 PM
```

Success! 

And the last thing for today...

### How do we assign PIM eligibility permanently?

What if you need to assign PIM eligibility with no expiration? That is tricky. 

By default, Entra ID supports a policy that disallows PIM eligibility longer than one year.

What to do? Correct, edit the policy assigned to the PIM group!

To perform that we will require another PowerShell module

``` PowerShell

pwsh> Install-Module Microsoft.Graph.Identity.SignIns

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): y
pwsh> Import-Module Microsoft.Graph.Identity.SignIns

```
Then, prepare the variables and update the policy based on 
[Update a rule defined for a policy in PIM for Microsoft Entra roles](https://learn.microsoft.com/en-us/graph/api/unifiedrolemanagementpolicyrule-update?view=graph-rest-1.0&tabs=powershell#example-1-update-a-rule-defined-for-a-policy-in-pim-for-microsoft-entra-roles) and [expirationPattern resource type](https://learn.microsoft.com/en-us/graph/api/resources/expirationpattern?view=graph-rest-1.0)

``` PowerShell
pwsh> $p = Get-MgPolicyRoleManagementPolicyAssignment -Filter $("scopeId eq '{0}' and scopeType eq 'Group' and RoleDefinitionId eq 'member'" -f $pg01.Id)
pwsh> 
pwsh> $unifiedRoleManagementPolicyId = $p.PolicyId
pwsh> $unifiedRoleManagementPolicyRuleId = "Expiration_Admin_Eligibility"

pwsh> $params = @{
    "@odata.type" = "#microsoft.graph.unifiedRoleManagementPolicyExpirationRule"
    id = "Expiration_Admin_Eligibility"
    isExpirationRequired = $false
    target = @{
        "@odata.type" = "microsoft.graph.unifiedRoleManagementPolicyRuleTarget"
        caller = "Admin"
        operations = @(
            "All"
        )
        level = "Eligibility"
        inheritableSettings = @(
        )
        enforcedSettings = @(
        )
    }
}

pwsh> Update-MgPolicyRoleManagementPolicyRule -UnifiedRoleManagementPolicyId $unifiedRoleManagementPolicyId -UnifiedRoleManagementPolicyRuleId $unifiedRoleManagementPolicyRuleId -BodyParameter $params

Id
--
Expiration_Admin_Eligibility
```
Ta-da!

And now we are allowed to assign PIM eligibility permanently!

``` PowerShell

pwsh> $params = @{
	accessId = "member"
	principalId = "$($u01.Id)"
	groupId = "$($pg01.Id)"
	action = "AdminAssign"
	scheduleInfo = @{
		startDateTime = $(Get-Date)
        expiration    = @{
            type = "noExpiration"
        }
	}
	justification = "Assign eligible request."
}

pwsh> New-MgIdentityGovernancePrivilegedAccessGroupEligibilityScheduleRequest -BodyParameter $params

Action      ApprovalId CompletedDateTime     CreatedDateTime       CustomData Id                                   IsValidationOnly Justification            Status      AccessId GroupId                              PrincipalId
------      ---------- -----------------     ---------------       ---------- --                                   ---------------- -------------            ------      -------- -------                              -----------            
adminAssign            4/21/2024 11:43:25 PM 4/21/2024 11:43:24 PM            48624c8b-a008-4499-ab60-1922eab76da6 False            Assign eligible request. Provisioned member   853d7402-51b4-4cd4-9b8d-9f159311859d c8816325-d172-44f5-b72…

```
Let's look at the PIM eligibility assignment via the portal.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0z6j4am5uykfexttsghf.png)

Here it is!

## Final words 

Of course, there are many topics outside of this series, and I never wanted to cover everything. My idea was to cover the 'first steps'—the 'initial direction.' 

When I started, I found 0 (zero) explanations, and the documentation was in beta. I spent significant time trying and retrying the API calls to understand how they work. 

I recently found a lovely post about PIM for Groups: [Automate Assignments with the GraphAPI!](https://dikkekip.github.io/posts/pim-for-groups-1/). If I had seen it earlier, I would not have written mine. But I believe mine is slightly deeper. :) 

Thank you for being with me for that long. 

PS. All the tenants, subscriptions, and users from the examples are gone. Please don't bother to search for them. :)