Avoid disasters with Resource Locks in Azure

Category

Tips & Tricks

Published

March 17, 2017

We have probably all done it before, running a command and then seconds later realize that you just did a huge mistake and deleted things that shouldn't be deleted. Azure has a nice feature to mitigate this. It's called 'Resource Locks', and you enable them on your resources to prevent accidental deletion. The only way to delete the resource that has a lock, is to delete the lock. There's also an options 'ReadOnly' that not only prevents the resource from being deleted, but also from being updated.

The PowerShell Cmdlet for this is quite straight forward.

New-AzureRmResourceLock -LockName <name-of-lock> -LockLevel CanNotDelete -LockNotes <description-of-lock> -ResourceId <id-of-resource>

I think the best use of this is to put a lock on the whole target ResourceGroup since the lock is inherited and spans over all child resources. This way you don't have to put a lock on every single resource, but instead just target their parent.

Here's a small snippet to go through all the resource groups in your subscription and attach a resource lock to them:

Of course you can filter out and just apply it on some of the resource groups.

Another example, in this scenario we put resource locks on WebApps that are tagged with production.

Read more in Microsoft's documentation here: Lock resources to prevent unexpected changes

Written by

Karl Wallenius