Friday, December 22, 2023

Azure policy: Deploy CanNotDelete locks to resource groups

 You can use Azure policy to apply resource locks to all resource groups in a defined scope. This can be useful to ensure that critical resources are not deleted by mistake. See general description of resource locks here. Note that applying locks in the environment can create unforeseen problems so it's good to proceed with a bit of caution. 

The policy in this post is based on a slightly modified version from AzAdvertizer, that can be found here. The original policy will apply locks to a list of resource group names that is specified in an array.

The modified version, which can be found here on Github, applies locks to all resource groups but excludes resource groups which are specified in the array.

Note that the only built-in roles (for the system assigned managed identity, SAMI) that can apply locks are Owner and User Access Administrator. Owner has typically too many permissions and User Access Administrator does not have the policy deployment permissions. So a custom RBAC is required.

To create a custom RBAC, go the the subscription or management group level where the policy will be applied, go to Access Control (IAM) -> Roles. From here click +Add to a new role. Add the following permissions:

"Microsoft.Resources/deployments/write",
"Microsoft.Authorization/locks/*",
"Microsoft.Authorization/policies/deployIfNotExists/action",
"Microsoft.Resources/checkPolicyCompliance/read"

The full RBAC role in JSON can be found here on Github (make sure to update the management group or subscription under assignableScopes).

When you assign the policy definition, make sure to choose the new RBAC role when creating the SAMI, see below:





No comments:

Post a Comment

Note: Only a member of this blog may post a comment.