Tuesday, April 18, 2017

Checking for Resource Group Locks in Azure

When I deploy production architectures in Azure, I want to put protections in to the deployment that prevent accidental modification/deletion of business critical resources.  One such tool in Azure is the concept of resource locks.  At a bare minimum, I want to ensure that resource groups containing my production deployments have locks on them to prevent deletion.  The goal of this post is to showcase how to use powershell to double check that all required locks are in place.

    [Parameter(Mandatory=$true,HelpMessage="The search term for all resource groups to check")]

$resourceGroups = (Get-AzureRmResourceGroup | ? {$_.ResourceGroupName -like "*$search*"})

foreach ($resourceGroup in $resourceGroups){
    $lock = Get-AzureRmResourceLock -ResourceGroupName $resourceGroup.ResourceGroupName
    if ($lock -eq $null){
        Write-Host "$($resourceGroup.ResourceGroupName) is missing a lock"

The script above is really quite simple.  When I do production deployments, I usually place the word "prod" somewhere in the resource group name.  The script above takes in a search parameter and then tries to locate all resource groups that contain that search parameter.  The foreach loop essentially checks for the existence of a lock.  If no lock is found, a message is printed. 

This script could be expanded in several ways to be more robust.  For example, it could auto correct the condition by placing the required lock.  One could then add this as part of an Azure Automation job that would ensure that production resource groups are not left unprotected for long.  Further, it could actually look at the lock to determine if it is delete or read-only and report accordingly.

In any event, the above script suited my audit purposes just fine.  Enjoy!