Skip to main content

Command Palette

Search for a command to run...

Automating Azure PIM Role Elevation with PowerShell

Updated
2 min read
Automating Azure PIM Role Elevation with PowerShell

Azure Privileged Identity Management (PIM) is a crucial security feature that enables just-in-time role elevation for both Azure resources and Azure Entra roles. While this significantly enhances platform security by eliminating permanent active assignments, the traditional portal-based elevation process can introduce inefficiencies into development workflows.

The Challenge with Portal-Based Elevation

The Azure Portal interface for PIM, while functional, presents several operational friction points:

  • Time-consuming role selection, especially with multiple assignments

  • Significant context switching for developers working primarily in PowerShell

  • Interrupted development flow when managing multiple role elevations

A PowerShell-Based Solution

For developers who primarily work in PowerShell, here's a solution that simplifies the role elevation process:

param(
   [Parameter()]
   [string]$SubscriptionId,

   [Parameter()]
   [string[]]$RoleDefinitionName = @("Contributor", "User Access Administrator"),

   [Parameter()]
   [string]$Justification = "Local development",

   [Parameter()]
   [int]$DurationInHours = 8
)

$ErrorActionPreference = "Stop"

$currentContext = Get-AzContext

ForEach ($role in $RoleDefinitionName) {
   Write-Verbose "Elevating to role $role on subscription $SubscriptionId for $DurationInHours hours" -Verbose:$true
   $roleDefinitionId = (Get-AzRoleDefinition -Name $role).Id
   $inputObject = @{
       Name = [guid]::NewGuid().ToString()
       Scope = "/subscriptions/$subscriptionId/"
       ExpirationDuration = "PT${DurationInHours}H"
       ExpirationType = "AfterDuration"
       PrincipalId = (Get-AzAdUser -Mail $currentContext.Account.Id).Id
       RequestType = "SelfActivate"
       RoleDefinitionId = "/subscriptions/$SubscriptionId/providers/Microsoft.Authorization/roleDefinitions/$roleDefinitionId"
       ScheduleInfoStartDateTime = Get-Date -Format o
       Justification = $Justification
       Verbose = $false
   }

   New-AzRoleAssignmentScheduleRequest @inputObject
}

Implementation Guide

  1. Save the script as Elevate-PimRole.ps1

  2. Execute with your subscription ID:

./Elevate-PimRole.ps1 -SubscriptionId xxxxxxxx-xxxx-xxxx-xxxxxxxx

Important Considerations

  • The default configuration elevates both Contributor and User Access Administrator roles

  • The script assumes subscription-level scope; modify the scope parameter for resource group-level operations

  • Default elevation duration is set to 8 hours

  • Custom justification messages can be provided via the -Justification parameter

This approach maintains security while significantly improving developer productivity by eliminating unnecessary context switching and portal navigation.

M

Hey, thanks for the blog post!

1