Manage Azure RBAC using Power Shell

Azure role-based access control (Azure RBAC) helps you manage who has access to Azure resources, what they can do with those resources, and what areas they have access to.
Before we start first review basics from Microsoft document on RBAC here. Like one of the important concept is scope. When you assign a role, you can further limit the actions allowed by defining a scope. Scopes are structured in a parent-child relationship.

Giving right access is always being challenging and very important. In this article I will focus on PowerShell Az module to manage RBAC roles. To install latest Powershell Az module, please refer here.

#Get resource details
Get-AzResource | Export-Csv -Path "G:\azureinventory1.csv"
Get-AzResource -name '<resource name>' | select Name, resourcetype, resourceid

#show resources group by location
Get-AzResourceGroup | Sort Location,ResourceGroupName | Format-Table -GroupBy Location ResourceGroupName,ProvisioningState,Tags

#List all RBAC roles end with contributer name
Get-AzRoleDefinition | Where-Object { $_.Name -like '*Contributor'} | select Name,Description
Get-AzRoleDefinition | Where Name -like '*Contributor' | select Name,Description

<# NOTE: similarly for where clause you can use below

-ne (not equal to)
-lt (less than)
-le (less than or equal to)
-gt (greater than)
-ge (greater than or equal to)
-like (like—a wildcard comparison)
-notlike (not like—a wildcard comparison)
-contains (contains the specified value)
-notcontains (doesn't contain the specified value)
#>

#List role assignments at RG scope level
Get-AzRoleAssignment -ResourceGroupName "<RGname>" | select DisplayName,RoleDefinitionName | select-object -first 2
Get-AzRoleAssignment | select SignInName,RoleDefinitionName,Scope | Where-Object { $_.SignInName -ne $null}

Get-Help New-AzRoleAssignment
<#   
SYNOPSIS
    Assigns the specified RBAC role to the specified principal, at the specified scope.

DESCRIPTION
    Use the New-AzRoleAssignment command to grant access. Access is granted by assigning the appropriate RBAC role to them at the right scope. To grant access to the entire subscription, assign a role at the subscription scope. To grant access to a specific resource group within a subscription, assign a role at the resource group scope. The subject of the assignment must be specified. To specify a user, use SignInName or Azure AD ObjectId parameters. To specify a security group, use Azure AD ObjectId parameter. And to specify an Azure AD application, use ApplicationId or ObjectId parameters. The role that is being assigned must be specified using the RoleDefinitionName parameter. The scope at which access is being granted may be specified. It defaults to the selected subscription.  The scope of the assignment can be specified using one of the following parameter combinations         
 a. Scope - This is the fully qualified scope starting with /subscriptions/<subscriptionId>
 b. ResourceGroupName - to grant access to the specified resource group.
 c. ResourceName, ResourceType, ResourceGroupName and (optionally) ParentResource - to specify a particular resource within a resource group to grant access to.
#>

Get-help New-AzRoleAssignment -examples

#Grant Reader role access to a user at a resource group scope with the Role Assignment being available for delegation
New-AzRoleAssignment -ResourceGroupName rg1 -SignInName allen.young@live.com -RoleDefinitionName Reader -AllowDelegation
   
#Grant access to a security group
Get-AzADGroup -SearchString "Christine Koch Team"
   
#DisplayName          Type  Id
#-----------          ----  --------
#Christine Koch Team        2f9d4375-cbf1-48e8-83c9-2a0be4cb33fb
   
New-AzRoleAssignment -ObjectId 2f9d4375-cbf1-48e8-83c9-2a0be4cb33fb -RoleDefinitionName Contributor  -ResourceGroupName rg1
   
#Grant access to a group at a nested resource (subnet)
New-AzRoleAssignment -ObjectId 5ac84765-1c8c-4994-94b2-629461bd191b -RoleDefinitionName "Virtual Machine Contributor" -ResourceName Devices-Engineering-ProjectRND -ResourceType Microsoft.Network/virtualNetworks/subnets -ParentResource virtualNetworks/VNET-EASTUS-01 -ResourceGroupName Network

#Grant reader access to a service principal
$servicePrincipal = New-AzADServicePrincipal -DisplayName "testServiceprincipal"
New-AzRoleAssignment -RoleDefinitionName "Reader" -ApplicationId $servicePrincipal.ApplicationId

#Removes a role assignment for john.doe@contoso.com who is assigned to the Reader role at the rg1 resourcegroup scope.
Remove-AzRoleAssignment -ResourceGroupName rg1 -SignInName john.doe@contoso.com -RoleDefinitionName Reader

#Removes the role assignment to the group principal identified by the ObjectId and assigned to the Reader role. Defaults to using the current subscription as the scope to find the assignment to be deleted.
Remove-AzRoleAssignment -ObjectId 36f81fc3-b00f-48cd-8218-3879f51ff39f -RoleDefinitionName Reader

#Removes the first role assignment object which is fetched from the Get-AzRoleAssignment commandlet.
$roleassignment = Get-AzRoleAssignment |Select-Object -First 1 -Wait
Remove-AzRoleAssignment -InputObject $roleassignment

#lists just the custom roles that are available for assignment in the selected subscription.
Get-AzRoleDefinition | ? {$_.IsCustom -eq $true} | FT Name, IsCustom

#Create a custom role, in below remove id, update all details
Get-AzRoleDefinition "HDInsight Cluster Operator" | ConvertTo-Json
{
    "Name":  "HDInsight Cluster Operator",
    "Id":  "61ed4efc-fab3-44fd-b111-e24485cc132a",
    "IsCustom":  false,
    "Description":  "Lets you read and modify HDInsight cluster configurations.",
    "Actions":  [
                    "Microsoft.HDInsight/*/read",
                    "Microsoft.HDInsight/clusters/getGatewaySettings/action",
                    "Microsoft.HDInsight/clusters/updateGatewaySettings/action",
                    "Microsoft.HDInsight/clusters/configurations/*",
                    "Microsoft.Resources/subscriptions/resourceGroups/read",
                    "Microsoft.Resources/deployments/operations/read",
                    "Microsoft.Insights/alertRules/*",
                    "Microsoft.Authorization/*/read",
                    "Microsoft.Support/*"
                ],
    "NotActions":  [

                   ],
    "DataActions":  [

                    ],
    "NotDataActions":  [

                       ],
    "AssignableScopes":  [
                             "/"
                         ]
}

#Create a custom role with JSON template
New-AzRoleDefinition -InputFile "C:\CustomRoles\customrole1.json"
#Example Jason
{
  "Name": "Custom Role 1",
  "Id": null,
  "IsCustom": true,
  "Description": "Allows for read access to Azure storage and compute resources and access to support",
  "Actions": [
    "Microsoft.Compute/*/read",
    "Microsoft.Storage/*/read",
    "Microsoft.Support/*"
  ],
  "NotActions": [],
  "AssignableScopes": [
    "/subscriptions/00000000-0000-0000-0000-000000000000",
    "/subscriptions/11111111-1111-1111-1111-111111111111"
  ]
}

#Create a custom role with the PSRoleDefinition object
$role = Get-AzRoleDefinition "Virtual Machine Contributor"
$role.Id = $null
$role.Name = "Virtual Machine Operator"
$role.Description = "Can monitor and restart virtual machines."
$role.Actions.Clear()
$role.Actions.Add("Microsoft.Storage/*/read")
$role.Actions.Add("Microsoft.Network/*/read")
$role.Actions.Add("Microsoft.Compute/*/read")
$role.Actions.Add("Microsoft.Compute/virtualMachines/start/action")
$role.Actions.Add("Microsoft.Compute/virtualMachines/restart/action")
$role.Actions.Add("Microsoft.Authorization/*/read")
$role.Actions.Add("Microsoft.ResourceHealth/availabilityStatuses/read")
$role.Actions.Add("Microsoft.Resources/subscriptions/resourceGroups/read")
$role.Actions.Add("Microsoft.Insights/alertRules/*")
$role.Actions.Add("Microsoft.Support/*")
$role.AssignableScopes.Clear()
$role.AssignableScopes.Add("/subscriptions/00000000-0000-0000-0000-000000000000")
$role.AssignableScopes.Add("/subscriptions/11111111-1111-1111-1111-111111111111")
New-AzRoleDefinition -Role $role

#Update a custom role with Json
Set-AzRoleDefinition -InputFile "C:\CustomRoles\customrole1.json"

#The following example adds the Microsoft.Insights/diagnosticSettings/* operation to the Virtual Machine Operator custom role.
$role = Get-AzRoleDefinition "Virtual Machine Operator"
$role.Actions.Add("Microsoft.Insights/diagnosticSettings/*")
Set-AzRoleDefinition -Role $role

#The following example adds an Azure subscription to the assignable scopes of the Virtual Machine Operator custom role.
Get-AzSubscription -SubscriptionName Production3
$role = Get-AzRoleDefinition "Virtual Machine Operator"
$role.AssignableScopes.Add("/subscriptions/22222222-2222-2222-2222-222222222222")
Set-AzRoleDefinition -Role $role

#removes the Virtual Machine Operator custom role
Get-AzRoleDefinition "Virtual Machine Operator" | Remove-AzRoleDefinition
# or remove with id
Remove-AzRoleDefinition -Id "1122.32223.3344.2233.2233"

#lists just the actions of the role:
(Get-AzRoleDefinition "Virtual Machine Contributor").Actions
   
# Microsoft.Authorization/*/read
# Microsoft.Compute/availabilitySets/*
# Microsoft.Compute/locations/*
# Microsoft.Compute/virtualMachines/*
# Microsoft.Compute/virtualMachineScaleSets/*
# Microsoft.DevTestLab/schedules/*
# Microsoft.Insights/alertRules/

#available operations for virtual machines
Get-AzProviderOperation "Microsoft.Compute/virtualMachines/*" | FT OperationName, Operation, Description -AutoSize

<#
OperationName                    Operation                                         Description                                                                                   
-------------                    ---------                                         -----------                                                                                  
Get Virtual Machine              Microsoft.Compute/virtualMachines/read            Get the properties of a virtual machine                                                      
Create or Update Virtual Machine Microsoft.Compute/virtualMachines/write           Creates a new virtual machine or updates an existing virtual machine                         
Delete Virtual Machine           Microsoft.Compute/virtualMachines/delete          Deletes the virtual machine                                                                  
Start Virtual Machine            Microsoft.Compute/virtualMachines/start/action    Starts the virtual machine                                                                   
Power Off Virtual Machine        Microsoft.Compute/virtualMachines/powerOff/action Powers off the virtual machine. Note that the virtual machine will continue to be billed.    
-------                                                   
#>

Post a Comment

Thanks for your comment !
I will review your this and will respond you as soon as possible.