How to remove all empty or lockless Resource Groups using Azure CLI

Sometimes a little cleanup is needed on our subscriptions. The simplest way to clean up is, of course, to delete empty and not needed Resource Groups. Let's do it in Azure CLI.

With empty RGs it's quite easy - just list all RGs and for each RG check if there are resources in it - if no, then delete:

for i in `az group list -o tsv --query [].name`; do if [ "$(az resource list -g $i -o tsv)" ]; then echo "$i is not empty"; else az group delete -n $i -y --no-wait; fi; done

Cleaning not-empty RGs is much more complicated because we need to decide which of them are needed and which are not. The quickest way to do it is to add Delete Lock to every RG we want to leave untouched. Then we just need to iterate all RGs (as in previous example) and for each RG check if there is any Lock on it. If no Lock, then delete:

for i in `az group list -o tsv --query [].name`; do if [ "$(az lock list -g $i -o tsv --query [].name)" ]; then echo "$i have a lock"; else az group delete -n $i -y --no-wait; fi; done
comments powered by Disqus