Azure batch delete empty Resource Groups

Azure batch delete empty Resource Groups
When Azure Resource Groups gradually untidy over long periods of times, it can be easy to ignore these. A little automation along the way helps with this.

Let's say you have been working with Azure for some time and you have accumulated a number of resources across multiple resource groups. You wanted to keep things tidy back then, but now it has become messy and your Azure Resource Groups need to be cleaned up.

You can do that from the Azure Portal but that will take time figuring out which resource groups have resources and which ones do not!!. We can very easily automate this mess:

Over time, learning Azure means that lots of random resource groups can be created which leaves our subscription quite messy and will need cleaning up

Azure CLI to clean up unused Resource groups

Login to your Azure account via the Azure CLI, specifying the subscription if you happen to have multiple. We'll be using a Powershell command window

az login

##alternative targeting subscription
az login --subscription "<YOUR_TARGET_SUBSCRIPTION_ID_OR_NAME>"

Login to azure subscription

Create a powershell script (.ps1) for storing the following code (with the filename resourceCleaner.ps1 for example):

# Get resource group names
$resourceGroups = & az.cmd group list --query "[].name" --output tsv

foreach ($rg in $resourceGroups) {
    # Retrieve resources as JSON and convert to objects
    $resourcesJson = & az.cmd resource list --resource-group $rg --output json
    $resources = $resourcesJson | ConvertFrom-Json

    # Check if the current resource group is empty, then delete
    if ($resources.Count -eq 0) {
        Write-Host "Deleting empty resource group: $rg"
        & az.cmd group delete --name $rg --yes --no-wait
    }
}

Powershell for executing Azure Resource cleanup

Run the Powershell script in an Administrative Powershell Window:

##navigate to the path with your ps1 file, bypass the Execution Policy for this particular file

powershell.exe -ExecutionPolicy Bypass -File .\resourceGroupCleaner.ps1

Execute ps1 file with Execution bypass

The output should look like the following as resource groups are removed.

My Results of unused Resource Groups

This will be helpful over time for managing empty and dormant Resource Groups. Happy Azure Learning!!