Use PowerShell to Add ACL, permission or Role assignment on all objects in all subscriptions


azure

The following script is made for those of you who has many subscriptions, or many objects, and you want to do something with them…
In my case, I needed to add the DBA’s AAD Group as Reader to all the disks of the SQL Server VM’s. Migrated servers, 6 disks each…you do not want to do that manually in the portal…

Run it a PowerShell tool of choice, prompt from script, ISE, VS Code or in CloudShell.
! However, there is a verified bug in a Az module used by New-AzRoleAssignment, tested and verified to work in CloudShell with Az module az.resources 2.5.1

  • Get-AzDisk can be replaced with Get-AzXXX to get any type of object you need.
  • New-AzRoleAssignment can be replaced with just about anything you want to do to the objects.
# Adds a Role assignment(ACL/RBAC) on all disks in all subscriptions based on strings in disks names
# In this example, the AAD Group ‘AAD-Group’ is added as Reader on all disks in all subscriptions, where the disks name contains the keywords: VM1, VM2 or SQL1
 
$Group = Get-AzADGroup -SearchString “AAD-Group”
$MySubs = Get-AzSubscription
Foreach ($Sub in $MySubs){
    Write-host $Sub.name
    Select-AzSubscription $sub.Name
    $Disks = Get-AzDisk | Where-Object { $_.Name -match ‘VM1’ -or $_.Name -match ‘VM2’ -or $_.Name -match ‘SQL1’}

    ForEach ($Disk in $Disks){
        Write-Host $Disk.name
        # Reader, Contributor, Owner, etc.
        New-AzRoleAssignment  -ObjectId $Group.Id -RoleDefinitionName ‘Reader’ -ResourceName $Disk.Name -ResourceGroupName $Disk.ResourceGroupName -ResourceType $Disk.Type
    }
}
 
– – – – – – – – – – – – – – – – – – – –
 
# Adds a Role assignment(ACL/RBAC) on all recovery vaults in all subscriptions
# In this example, the AAD Group ‘AAD-Group’ is added as Reader on all Recovery vaults in all subscriptions.
$Group = Get-AzADGroup -SearchString “AAD-Group”
$MySUbs = Get-AzSubscription # Get-AzSubscription
#Write-Output $MySubs
Foreach ($Sub in $MySubs){
    Write-host $Sub.name
    Select-AzSubscription $sub.Name
    $Vaults = Get-AzRecoveryServicesVault

    ForEach ($Vault in $Vaults){
        Write-Host $Vault.name
        # Reader, Contributor, Owner, etc.
        New-AzRoleAssignment  -ObjectId $Group.Id -RoleDefinitionName ‘Reader’ -ResourceName $Vault.Name -ResourceGroupName $Vault.ResourceGroupName -ResourceType $Vault.Type
    }
}
 
Happy PowerShell scripting!
 

References
https://docs.microsoft.com/en-us/powershell/azure/install-az-ps


___________________________________________________________________________________________________

Enjoy!

Regards

 Thomas Odell Balkeståhl on LinkedIn

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s