Creating Custom Role through Power Shell script
While dealing with Role based access control – RBAC there may be a need to create a custom role in spite of using built-in roles available in azure. Following lab will help you to create custom role using Azure CLI with PowerShell script.
On the top bar of azure portal click on following icon which will open Azure Shell as bottom bar of the Azure portal.
Remember if you are doing this first time in your account then this will show you prompt to create a new storage account which will associate with this shell and second it will ask you which scripting platform you want to use from Bash or PowerShell.
If you have configured storage and PowerShell for this then it will show you following screen.
You can anytime switch from PowerShell to back by clicking on drop-down which is available at the left top corner.
Once you get this prompt you can execute following script or fire these commands to create a new custom role with name Virtual Machine Operator
PowerShell Script
Get-AzProviderOperation “Microsoft.Compute/virtualMachines/*” | FT OperationName, Operation, Description –AutoSize
$sub=Get-AzSubscription -SubscriptionName “Free Trial”
$role=Get-AzRoleDefinition “Virtual Machine Contributor”
$role.actions
$role.Id=$null
$role.Name=”Virtual Machine Operator”
$role.Description = “He Can monitor and restart virtual machines.”
$role.Actions.Remove(“Microsoft.Compute/virtualMachines/*”)
$role.Actions.Remove(“Microsoft.Compute/virtualMachineScaleSets/*”)
$role.Actions.Add(“Microsoft.Compute/virtualMachines/read”)
$role.Actions.Add(“Microsoft.Compute/virtualMachines/start/action”)
$role.Actions.Add(“Microsoft.Compute/virtualMachines/restart/action”)
$role.AssignableScopes.Clear()
$role.AssignableScopes.Add(“/subscriptions/$($sub.id)”)
New-AzRoleDefinition -Role $role
To understand above script kindly focus on following points.
- $sub and $role are variables which we have created
- Instead of Free Trial you can put your subscription name
- We are using existing role Virtual Machine Contributor
- Using existing role properties, we are creating new custom role
- We are first removing some actions and then adding some in to this role
- Using these actions, we can control what a user can do with this role
- Finally, before creating this role we are defining scope for this role
- As the scope of this role is at subscription level this can be used in multiple resource groups and in multiple VMs in those resource groups
- What’s Your Version Of “YOU CAN, IF YOU..” - January 28, 2022
- 20 days road map plan for Microsoft Azure Certification - April 21, 2021
- Bird’s eye view of Azure Arc - April 21, 2021