Introduction
Microsoft announced a new functionality within Azure Policy which allows admins to create action based effects. This functionality is in preview at the moment of writing but will be GA soon. Currently it only supports the “delete” action. In this blog I will show you how you can leverage Azure Policy with a DenyAction effect to prevent deletion of Azure Resources regardless of any roles.
Prerequisites
- Azure PowerShell Module
- Bicep Module
- Owner permissions to create policies
What are we creating
We’re creating a Bicep template that creates two Resource Types. A Policy Definition and a Policy Assignment. In the definition we will declare which effect we want to apply, in this case we’ll create an effect that denies deletion from Azure VMs but this will also work for other Resource Types. In the Policy Assignment we will declare the scope of the policy. We could scope this to a single Resource, Resource Group, Subscription or Management Group. In this case we’ll scope it to a Subscription.
Bicep Template
Log in to Azure and make sure you selected the correct subscription.
Deploy the bicep file with the following command and fill in your own file path and region.
new-azdeployment -templatefile "file path" -location "region"
targetScope = 'subscription' resource resPolicyDefinition 'Microsoft.Authorization/policyDefinitions@2021-06-01' = { name: 'Deny VM Deletion' properties: { displayName: 'Deny VM Deletion' description: 'Denies the deletion of virtual machines' metadata: { category: 'Virtual Machines' } policyRule: { if: { field: 'type' equals: 'Microsoft.Compute/virtualMachines' } then: { effect: 'DenyAction' details: { actionNames: ['Delete'] } } } } } resource ResPolicyAssignment 'Microsoft.Authorization/policyAssignments@2021-06-01' = { name: 'Deny VM Deletion' scope: subscription() properties: { displayName: 'Deny VM Deletion' description: 'Denies the deletion of virtual machines' policyDefinitionId: resPolicyDefinition.id } }
Result
After deployment you should see your newly created policy appear.
When we try to delete any Virtual Machine within the scoped subscription we receive an Azure Policy error as expected