Skip to content

Azure

How to create assigment Reports for Azure RBAC

Role-Based Access Control (RBAC) is a key feature of Azure that allows you to manage access to Azure resources. With RBAC, you can grant permissions to users, groups, and applications at a certain scope, such as a subscription, resource group, or resource. RBAC uses role assignments to determine what actions a user, group, or application can perform on a resource.

In this article, we will show you how to create reports for role assignments in Azure using PowerShell and the ImportExcel module. We will generate separate Excel files for role assignments at the subscription and management group levels, including information such as the role, principal, scope, and whether the assignment is inherited.

Role assignment report in Excel

This is the PowerShell script that generates the role assignment reports:

# Parameters setup
param (
    [Parameter(Mandatory=$false)]
    [string]$SubscriptionId,

    [Parameter(Mandatory=$false)]
    [string]$ManagementGroupName,

    [Parameter(Mandatory=$false)]
    [bool]$GetSubscriptions = $false,

    [Parameter(Mandatory=$false)]
    [bool]$GetManagementGroups = $true
)


# Install the ImportExcel module if not already installed
if (!(Get-Module -ListAvailable -Name ImportExcel)) {
    Install-Module -Name ImportExcel -Scope CurrentUser
}

# Define the path to your Excel file for Managing Group role assignments
$managementGroupPath = ".\AzRoleAssignmentMg.xlsx"
# Define the path to your Excel file for Subscription role assignments
$subscriptionPath = ".\AzRoleAssignmentSub.xlsx"

# Initialize an empty array to hold all role assignments
$subscriptionRoleAssignments = @()
$managementGroupRoleAssignments = @()

if ($GetManagementGroups) {
    # Check if ManagementGroupName is provided
    if ($ManagementGroupName) {
        # Get role assignments for the specified management group
        $roleAssignments = Get-AzRoleAssignment -Scope "/providers/Microsoft.Management/managementGroups/$ManagementGroupName"

        # Add these role assignments to the management group role assignments array
        $managementGroupRoleAssignments += $roleAssignments

        # Add 'GroupName' and 'IsInherited' properties to each role assignment object
        $roleAssignments | ForEach-Object {
            $_ | Add-Member -NotePropertyName 'GroupDisplayName' -NotePropertyValue (Get-AzManagementGroup -GroupName $ManagementGroupName).DisplayName
            $_ | Add-Member -NotePropertyName 'GroupName' -NotePropertyValue $ManagementGroupName
            # If the Scope of the role assignment is equal to the Id of the management group,
            # then the role assignment is not inherited; otherwise, it is inherited.
            if ($_.Scope -eq "/providers/Microsoft.Management/managementGroups/$ManagementGroupName") {
                $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $false
            } else {
                $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $true
            }
        }

        # Export the role assignments to a new sheet in the Excel file
        $roleAssignments | Export-Excel -Path $managementGroupPath -WorksheetName (Get-AzManagementGroup -GroupName $ManagementGroupName).DisplayName -AutoSize -AutoFilter
    } else {
        # Get all management groups
        $managementGroups = Get-AzManagementGroup
        # Loop through each management group
        foreach ($mg in $managementGroups) {
            # Get role assignments for the current management group
            $roleAssignments = Get-AzRoleAssignment -Scope "/providers/Microsoft.Management/managementGroups/$($mg.Name)"

            # Add these role assignments to the management group role assignments array
            $managementGroupRoleAssignments += $roleAssignments

            # Add 'GroupName' and 'IsInherited' properties to each role assignment object
            $roleAssignments | ForEach-Object {
                $_ | Add-Member -NotePropertyName 'GroupDisplayName' -NotePropertyValue $mg.DisplayName
                $_ | Add-Member -NotePropertyName 'GroupName' -NotePropertyValue $mg.Name
                # If the Scope of the role assignment is equal to the Id of the management group,
                # then the role assignment is not inherited; otherwise, it is inherited.
                if ($_.Scope -eq $mg.Id) {
                    $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $false
                } else {
                    $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $true
                }
            }

            # Export the role assignments to a new sheet in the Excel file
            $roleAssignments | Export-Excel -Path $managementGroupPath -WorksheetName $mg.DisplayName -AutoSize -AutoFilter
        }
}

if ($GetSubscriptions) {   
    # Check if SubscriptionId is provided
    if ($SubscriptionId) {
        # Get role assignments for the specified subscription
        $roleAssignments = Get-AzRoleAssignment -Scope "/subscriptions/$SubscriptionId"

        # Add these role assignments to the subscription role assignments array
        $subscriptionRoleAssignments += $roleAssignments

        # Add 'SubscriptionName' and 'IsInherited' properties to each role assignment object
        $roleAssignments | ForEach-Object { 
            $_ | Add-Member -NotePropertyName 'SubscriptionName' -NotePropertyValue (Get-AzSubscription -SubscriptionId $SubscriptionId).Name 
            $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $false
        }

        # Export the role assignments to a new sheet in the Excel file
        $roleAssignments | Export-Excel -Path $subscriptionPath -WorksheetName (Get-AzSubscription -SubscriptionId $SubscriptionId).Name -AutoSize -AutoFilter
    } else {
        # Get all subscriptions
        $subscriptions = Get-AzSubscription

        # Loop through each subscription
        foreach ($sub in $subscriptions) {
            # Get role assignments for the current subscription
            $roleAssignments = Get-AzRoleAssignment -Scope "/subscriptions/$($sub.SubscriptionId)"

            # Add these role assignments to the subscription role assignments array
            $subscriptionRoleAssignments += $roleAssignments

            # Add 'SubscriptionName' and 'IsInherited' properties to each role assignment object
            $roleAssignments | ForEach-Object { 
                $_ | Add-Member -NotePropertyName 'SubscriptionName' -NotePropertyValue $sub.Name
                 # If the Scope of the role assignment is equal to the subscription Id,
                 # then the role assignment is not inherited; otherwise, it is inherited.
                if ($_.Scope -eq "/subscriptions/$($sub.Id)") {
                    $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $false
                } else {
                    $_ | Add-Member -NotePropertyName 'IsInherited' -NotePropertyValue $true                }

            }

            # Export the role assignments to a new sheet in the Excel file
            $roleAssignments | Export-Excel -Path $subscriptionPath -WorksheetName $sub.Name -AutoSize -AutoFilter
        }
    }
}

This script takes the following parameters:

  • GetSubscriptions: A switch parameter that specifies whether to generate reports for subscriptions. The default value is $false.
  • GetManagementGroups: A switch parameter that specifies whether to generate reports for management groups. The default value is $true.
  • SubscriptionId: The ID of the subscription for which you want to generate the report. If this parameter is not provided, the script will generate reports for all subscriptions.
  • ManagementGroupName: The name of the management group for which you want to generate the report. If this parameter is not provided, the script will generate reports for all management groups.

Role definition report in Excel 1

You can also generate a report for role definitions in Azure using the following PowerShell script:

param(
    [Parameter(Mandatory=$false)]
    [ValidateSet('Console', 'Excel')]
    [string]$OutputType = 'Console',

    [Parameter(Mandatory=$false)]
    [string]$ExcelFilePath = ".\AzRoleDefinition.xlsx"
)

# Install the ImportExcel module if not already installed
if (!(Get-Module -ListAvailable -Name ImportExcel)) {
    Install-Module -Name ImportExcel -Scope CurrentUser
}

# Install the  AzureRM module if not already installed
if (!(Get-Module -ListAvailable -Name  Az)) {
    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    Install-Module -Name  Az -Scope CurrentUser
}

# Get all role definitions
$roleDefinitions = Get-AzRoleDefinition | ForEach-Object {
    # Create a custom object with ordered properties
    $customObject = New-Object PSObject -Property @{
        Name = $_.Name
        Id = $_.Id
        IsCustom = $_.IsCustom
        Description = $_.Description
        Actions = ($_.Actions -join ', ').Replace(',', ",`n")
        NotActions = ($_.NotActions -join ', ').Replace(',', ",`n")
        DataActions = ($_.DataActions -join ', ').Replace(',', ",`n")
        NotDataActions = ($_.NotDataActions -join ', ').Replace(',', ",`n")
        AssignableScopes = ($_.AssignableScopes -join ', ').Replace(',', ",`n")
    } | Select-Object Name, Id, IsCustom, Description, Actions, NotActions, DataActions, NotDataActions, AssignableScopes

    return $customObject
}

if ($OutputType -eq 'Console') {
    # Output to console
    $roleDefinitions | Format-Table -AutoSize
} else {
    # Export to Excel
    $roleDefinitions | Export-Excel -Path $ExcelFilePath -WorksheetName 'Role Definitions' -AutoSize -AutoFilter    
}

This script takes the following parameters:

  • OutputType: A string parameter that specifies the output type. The default value is 'Console'. You can also specify 'Excel' to export the report to an Excel file.
  • ExcelFilePath: The path to the Excel file where you want to export the report. The default value is ".\AzRoleDefinition.xlsx".

In the Excel report, you will see the following columns for each role definition: Name, Id, IsCustom, Description, Actions, NotActions, DataActions, NotDataActions, and AssignableScopes.

Role definition report in Excel 1

In this report we generate a report for role definitions in Azure with three columns: Name, JsonDefinition and IsCustom

You can also generate a report for role definitions in Azure using the following PowerShell script:

```powershell param( [Parameter(Mandatory=$false)] [ValidateSet('Console', 'Excel')] [string]$OutputType = 'Console',

[Parameter(Mandatory=$false)]
[string]$ExcelFilePath = ".\AzRoleDefinition.xlsx"

)

Install the ImportExcel module if not already installed

if (!(Get-Module -ListAvailable -Name ImportExcel)) { Install-Module -Name ImportExcel -Scope CurrentUser }

Install the AzureRM module if not already installed

if (!(Get-Module -ListAvailable -Name Az)) { Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser Install-Module -Name Az -Scope CurrentUser }

Get all role definitions

$roleDefinitions = Get-AzRoleDefinition | ForEach-Object { # Create a custom object with ordered properties $customObject = New-Object PSObject -Property @{ Name = $.Name JsonDefinition = ($ | ConvertTo-Json -Depth 10 -Compress) IsCustom = $_.IsCustom } | Select-Object Name, JsonDefinition, IsCustom

return $customObject

}

if ($OutputType -eq 'Console') { # Output to console $roleDefinitions | Format-Table -AutoSize } else { # Export to Excel $roleDefinitions | Export-Excel -Path $ExcelFilePath -WorksheetName 'Role Definitions' -AutoSize -AutoFilter
}

Azure Role-Based Access Control (RBAC)

Azure Role-Based Access Control (RBAC) is a system that provides fine-grained access management of resources in Azure. This allows administrators to grant only the amount of access that users need to perform their jobs.

Overview

In Azure RBAC, you can assign roles to user accounts, groups, service principals, and managed identities at different scopes. The scope could be a management group, subscription, resource group, or a single resource.

Here are some key terms you should know:

  • Role: A collection of permissions. For example, the "Virtual Machine Contributor" role allows the user to create and manage virtual machines.
  • Scope: The set of resources that the access applies to.
  • Assignment: The act of granting a role to a security principal at a particular scope.

Built-in Roles

Azure provides several built-in roles that you can assign to users, groups, service principals, and managed identities. Here are a few examples:

  • Owner: Has full access to all resources including the right to delegate access to others.
  • Contributor: Can create and manage all types of Azure resources but can’t grant access to others.
  • Reader: Can view existing Azure resources.
{
  "Name": "Contributor",
  "Id": "b24988ac-6180-42a0-ab88-20f7382dd24c",
  "IsCustom": false,
  "Description": "Lets you manage everything except access to resources.",
  "Actions": [
    "*"
  ],
  "NotActions": [
    "Microsoft.Authorization/*/Delete",
    "Microsoft.Authorization/*/Write",
    "Microsoft.Authorization/elevateAccess/Action"
  ],
  "DataActions": [],
  "NotDataActions": [],
  "AssignableScopes": [
    "/"
  ]
}

Custom Roles

If the built-in roles don't meet your specific needs, you can create your own custom roles. Just like built-in roles, you can assign permissions to custom roles and then assign those roles to users.

{
  "Name": "Custom Role",
  "Id": "00000000-0000-0000-0000-000000000000",
  "IsCustom": true,
  "Description": "Custom role description",
  "Actions": [
    "Microsoft.Compute/virtualMachines/start/action",
    "Microsoft.Compute/virtualMachines/restart/action"
  ],
  "NotActions": [],
  "DataActions": [],
  "NotDataActions": [],
  "AssignableScopes": [
    "/subscriptions/{subscriptionId}"
  ]
}
Custom Roles has the same structure as built-in roles:

  • Name: The name of the custom role.
  • Id: A unique identifier for the custom role.
  • IsCustom: Indicates whether the role is custom or built-in.
  • Description: A description of the custom role.
  • Actions: The list of actions that the role can perform.
  • NotActions: The list of actions that the role cannot perform.
  • DataActions: The list of data actions that the role can perform.
  • NotDataActions: The list of data actions that the role cannot perform.
  • AssignableScopes: The list of scopes where the role can be assigned.

You can check how to create a custom role here and not forget to check limitations here.

Recommendations

Here are some best practices for managing access with Azure RBAC:

  • Use the principle of least privilege: Only grant the permissions that users need to do their jobs.
  • Use built-in roles when possible: Built-in roles are already defined and tested by Microsoft. Only create custom roles when necessary.
  • Regularly review role assignments: Make sure that users have the appropriate level of access for their job. Remove any unnecessary role assignments.

Conclusion

Azure RBAC is a powerful tool for managing access to your Azure resources. By understanding its core concepts and how to apply them, you can ensure that users have the appropriate level of access for their job.