Automate locking of all resources of a particular type - Code Sample
@20aman Dec 05, 2021Locking is a concept that is available on all Azure resources. Locks are a very important but very less known feature in Azure. This prevents unintended operation on a particular resource.
NOTE: We visited this concept in the past. Here we want to re-iterate this for our readers as I have observed many issues at various customers that could have been prevented if they were leveraging locks for all their critical resources.
You have two types of locks in Azure:
- ReadOnly - You won't' be able to alter any configuration of the resource
- DoNotDelete - You will be able to add configurations but will not be able to remove configurations or even delete the resource
Do Not Delete is the lock, that as a best practice, you should apply on all critical resources in the environment. Once this lock is there on the resources, even the global administrator will not be able to delete the resources. The only way to delete the resources will be to delete the lock first and then delete the resources.
The Script Sample Details
This script sample leverages this concept of locks and uses the below cmdlet to apply the locks on various critical resources in the environment.
New-AzureRmResourceLock -LockLevel CanNotDelete -LockName DoNotDelete -ResourceName $vNet.Name -ResourceType $vNet.Type -ResourceGroupName $vNet.ResourceGroupName -LockNotes "Do Not Delete Lock" -Confirm -Force
The above command uses New-AzureRmResourceLock cmdlet to create the Do Not Delete lock on a Virtual Network.
This script iterates through all subscriptions that your account has access to and then applies the lock to all resources of type:
- Virtual Network
- Route Tables
- Express Routes
- Virtual Network Gateways
- Virtual Network Gateway Connections
- Recovery Services Vaults (i.e. ASR Vaults)
You can add more resource types that you deem as critical in your environment.
Location of the Script
You can find this script in GitHub at this location: Apply-LocksOnVariousAzureResources.ps1