There’s a special kind of sinking feeling in your stomach when you realize that you (or someone on your team) inadvertently deleted your database, especially your production database. You've been there before: you ran a command and as soon as you hit enter you realize what you've done. You cancel the command as fast as possible, but it's too late, the damage is done. Time starts moving in slow motion. Seconds seem like minutes, minutes like hours. How much data have you lost, can you even get things back up, are your backups gone?
The cloud has many benefits, one being that you can easily spin up a resource. But it’s true that you can just as easily spin one down. The good news is that you can prevent accidental deletion of your Azure Database for PostgreSQL server (and other Azure resources) by using a *delete lock*. Delete locks are a type of management lock in Azure.
You can use one command in the Azure CLI to create a delete lock on your Postgres server:
Now if someone tries to delete this server or its resource group, they will get an error:
This scope cannot perform delete operation because following scope(s) are locked: '/subscriptions/00000000000000000000000000/resourcegroups/samplegroup/providers/Microsoft.DBforPostgreSQL/servers/thesampleserver'. Please remove the lock and try again.
You can even put a delete lock at the resource group level. One advantage of doing this is that new resources are automatically protected by the delete lock. This is a great way of protecting production resources from accidental deletion.
This command locks a resource group:
az lock create --lock-type CanNotDelete --name DeleteLockGroup --resource-group samplegroup
If someone tries to delete the group or a resource in that group, they will get an error.
Note: To create or delete a lock, you must have access to Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Owner and User Access Administrator are the two built-in roles that are granted those actions.
You can also implement delete locks using the Azure portal, as part of an ARM Template, PowerShell script, or REST API. Learn how to do so in the lock resources documentation. Integrating lock setup in your resource creation workflow will help safeguard against accidental disasters in the future.