Skip to content

arturkraina/azure-pim-cli

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 

Repository files navigation

Azure PIM Role Activation Script

A Bash script for activating Azure Privileged Identity Management (PIM) roles directly from the command line. This script provides an interactive way to activate eligible PIM roles on Azure subscriptions without using the Azure Portal.

Table of Contents

Overview

Azure Privileged Identity Management (PIM) allows organizations to manage, control, and monitor access to important resources. Users with eligible role assignments must activate their roles before use. This script automates the activation process via the Azure REST API.

Features

  • Interactive subscription selection with list of available subscriptions
  • Displays currently active PIM roles for each subscription
  • Supports Owner, Contributor, and Reader roles
  • Automatic detection of already active roles
  • Role extension support for already active roles
  • Configurable activation duration
  • Required justification input for audit compliance
  • Comprehensive error handling with helpful messages

Prerequisites

Before using this script, ensure you have the following installed:

Required Tools

  1. Azure CLI (az)

    # Install on Ubuntu/Debian
    curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
    
    # Install on macOS
    brew install azure-cli
    
    # Install on Windows (PowerShell)
    winget install Microsoft.AzureCLI
  2. jq (JSON processor)

    # Ubuntu/Debian
    sudo apt-get install jq
    
    # macOS
    brew install jq
    
    # Windows (via Chocolatey)
    choco install jq
  3. uuidgen (UUID generator)

    # Ubuntu/Debian (usually pre-installed)
    sudo apt-get install uuid-runtime
    
    # macOS (pre-installed)
    # Windows (use PowerShell alternative or WSL)

Azure Requirements

  • An Azure AD account with eligible PIM role assignments
  • The user must have at least one eligible role assignment configured in PIM
  • Proper PIM policies must be configured by your Azure administrator

Installation

  1. Download the script:

    curl -O https://raw.githubusercontent.com/your-repo/pim-activation.sh
  2. Make the script executable:

    chmod +x pim-activation.sh
  3. Configure the script with your settings (see Configuration)

Configuration

Before running the script, update the configuration section at the top of the file:

#-------------------------------------------------------------------------------
# CONFIGURATION - UPDATE THESE VALUES WITH YOUR OWN INFORMATION
#-------------------------------------------------------------------------------
DEFAULT_USER_EMAIL="[email protected]"      # Your Azure AD email address
DEFAULT_DURATION_HOURS=8                        # Default activation duration in hours
TENANT_ID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  # Your Azure Tenant ID

Finding Your Tenant ID

You can find your Azure Tenant ID using:

# Via Azure CLI
az account show --query tenantId -o tsv

# Or in Azure Portal:
# Azure Active Directory -> Overview -> Tenant ID

Usage

Run the script:

./pim-activation.sh

Interactive Prompts

The script will guide you through the following steps:

  1. User Email: Enter your Azure AD email or press Enter for default
  2. Subscription Selection: Choose from a numbered list of available subscriptions
  3. Role Selection: Choose Owner (1), Contributor (2), or Reader (3)
  4. Duration: Enter activation duration in hours or press Enter for default
  5. Justification: Enter a reason for the activation (required for audit)
  6. Confirmation: Review summary and confirm activation

Example Session

=== Azure PIM Role Activation Script ===
Tenant: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

[1/4] Checking Azure login...
Logged in successfully

User email [[email protected]]:

[2/4] Loading subscriptions...

  1) Production
      xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
      ✓ Active: Reader

  2) Development
      yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy

Select subscription [1-2]: 2

Select role:
  1) Owner
  2) Contributor
  3) Reader
Choice [1-3]: 1

Activation duration in hours [8]: 4
Justification (reason for activation): Deploy new application version

--- Summary ---
User:         [email protected]
Subscription: Development (yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy)
Role:         Owner
Duration:     4h
Justification: Deploy new application version

Proceed? [Y/n]: Y

[3/4] Checking role status...
Role: Owner (8e3af657-a8ff-443c-a75c-2fe8c4bcb635)
Role is not active, activating...

[4/4] Sending request...
============================================
✓ Role Owner successfully activated!
============================================

Details:
  Role:         Owner
  Subscription: Development
  Duration:     4h
  Request ID:   xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

How It Works

Step-by-Step Process

Step 1: Azure Authentication

The script first checks if you're logged into Azure CLI and connected to the correct tenant. If not, it initiates the login process:

az login --tenant "$TENANT_ID"

Step 2: Load Subscriptions

The script queries Azure for all subscriptions in the specified tenant:

az account list --query "[?tenantId=='${TENANT_ID}']"

For each subscription, it also checks for currently active PIM roles by querying the Role Assignment Schedule Instances API:

GET https://management.azure.com/subscriptions/{id}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances

Step 3: Check Role Status

Before activation, the script checks:

  1. Permanent Assignment: If the role is permanently assigned (not via PIM), activation is not needed
  2. Active PIM Assignment: If the role is already active via PIM, offers to extend instead

Step 4: Send Activation Request

The script constructs a JSON request body and sends it to the Azure PIM API:

PUT https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{requestId}

Request body structure:

{
    "properties": {
        "principalId": "{user-object-id}",
        "roleDefinitionId": "{role-definition-id}",
        "requestType": "SelfActivate",
        "justification": "{user-provided-justification}",
        "scheduleInfo": {
            "startDateTime": "{current-utc-time}",
            "expiration": {
                "type": "AfterDuration",
                "duration": "PT{hours}H"
            }
        }
    }
}

API Version

The script uses API version 2020-10-01 for the Role Assignment Schedule Requests endpoint.

Supported Roles

The script supports the following Azure built-in roles:

Role GUID Description
Owner 8e3af657-a8ff-443c-a75c-2fe8c4bcb635 Full access to all resources
Contributor b24988ac-6180-42a0-ab88-20f7382dd24c Create and manage all resources, no access grants
Reader acdd72a7-3385-48ef-bd42-f606fba81ae7 View all resources

To add more roles, update the get_role_guid() and get_role_name_by_guid() functions with the appropriate GUIDs. You can find role GUIDs using:

az role definition list --name "Role Name" --query "[].name" -o tsv

Error Handling

The script handles common errors with helpful messages:

Error Code Description Solution
RoleAssignmentExists Role already assigned Check Azure Portal IAM for existing assignments
RoleAssignmentDoesNotExist Cannot extend non-active role Activate the role first instead of extending
SubjectNotFound No eligible PIM assignment Contact admin to configure PIM eligibility

Troubleshooting

"No subscriptions found"

  • Verify your Tenant ID is correct
  • Ensure your account has access to subscriptions in this tenant
  • Try logging in again: az login --tenant <tenant-id>

"Unable to get User ID"

  • Verify the email address is correct
  • Ensure the user exists in Azure AD
  • Check if you have permissions to query Azure AD

Role activation fails with no error message

  • Check if MFA is required and complete it
  • Verify PIM policies allow self-activation
  • Check if approval is required for this role

Active roles not showing correctly

  • The script only detects Owner, Contributor, and Reader roles
  • Custom roles require adding their GUIDs to the script

Security Considerations

  • The script does not store any credentials
  • All authentication is handled by Azure CLI
  • Justification is logged for audit purposes
  • Consider restricting script access in shared environments

License

MIT License - Feel free to modify and distribute.

About

Command-line tool for activating Azure PIM (Privileged Identity Management) roles. Interactive subscription and role selection with support for role extension.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages