To create a resource group and apply a lock, deploy the template above at the subscription level. In this setup, the main Bicep file creates the resource group and then calls a module to apply the lock.
Bicep
targetScope = 'subscription'
param rgName string
param rgLocation string
resource createRg 'Microsoft.Resources/resourceGroups@2025-04-01 = {
name: rgName
location: rgLocation
}
module deployRgLock './lockRg.bicep' = {
name: 'lockDeployment'
scope: resourceGroup(createRg.name)
}
The module uses a separate Bicep file called lockRg.bicep to create the resource group lock.
resource createRgLock 'Microsoft.Authorization/locks@2020-05-01' = {
name: 'rgLock'
properties: {
level: 'CanNotDelete'
notes: 'Resource group and its resources should not be deleted.'
}
}
When locking a resource within the resource group, include the scope property in the lock definition. Set scope to the name of the resource you want to lock.
param hostingPlanName string
param location string = resourceGroup().location
var siteName = 'ExampleSite${uniqueString(resourceGroup().id)}'
The example below shows a template that creates an App Service Plan, a website, and a lock on the website. The lock includes the scope property, which is set to the website to ensure it protects that specific resource.
resource serverFarm 'Microsoft.Web/serverfarms@2024-11-01' = {
name: hostingPlanName
location: location
sku: {
tier: 'Free'
name: 'f1'
capacity: 0
}
properties: {
targetWorkerCount: 1
}
}
resource webSite 'Microsoft.Web/sites@2024-11-01' = {
name: siteName
location: location
properties: {
serverFarmId: serverFarm.name
}
}
resource siteLock 'Microsoft.Authorization/locks@2020-05-01' = {
name: 'siteLock'
scope: webSite
properties:{
level: 'CanNotDelete'
notes: 'Site should not be deleted.'
}
}
Closing thoughts
We discussed Azure Resource Locks as an excellent way to prevent accidental deletion or modification of resources.
Remember, locks aren’t foolproof; they prevent accidents but won’t stop intentional actions by authorised (or unauthorised) users. Always consider potential side effects on normal operations before applying them.