Skip to content

Instantly share code, notes, and snippets.

@cicorias
Created March 28, 2021 14:49
Show Gist options
  • Save cicorias/509f4dab5ba1669734169848511029a7 to your computer and use it in GitHub Desktop.
Save cicorias/509f4dab5ba1669734169848511029a7 to your computer and use it in GitHub Desktop.
find and delete azure resource groups based upon a tag
#!/usr/bin/env bash
## this script identifies resource groups that have a tag: delete=true and will
## attempt to delete first by examining locks and deleting those locks (only 1 is supported)
## and then delete the group
## CAUTION USE WITH EXTREME CARE AS THERE IS NO GOING BACK WHEN A RESOURCE GROUP IS DELETED
set -u
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color
echo -e "${RED}## CAUTION USE WITH EXTREME CARE AS THERE IS NO GOING BACK WHEN A RESOURCE GROUP IS DELETED${NC}"
items=$(az group list --query "[?tags.delete == 'true'].{name:name}" -o tsv)
delete_lock() {
rv=-1
if [ -z "$1" ]
then
echo "no lock was supplied for $2"
else
rv=$(az group lock delete --name $1 --resource-group $2)
rv=$?
echo "d.lock: rv: $? --- $rv"
fi
return $rv
}
for i in $items
do
echo -e "${GREEN} locks for: $i${NC}"
locks=$(az group lock list -g "$i" --query '[].name')
if [ -z "$locks" ]
then
echo "${RED}$i is NOT locked${NC}"
rv=$(az group delete --resource-group $i --yes --verbose --no-wait)
else
lockname=$(az group lock list -g $i | jq -r '.[].name' )
echo -e "${GREEN}$i is locked using $lockname${NC}"
rv=$(delete_lock $lockname $i)
if [ "$?" -eq "0" ]
then
echo -e "${GREEN}attempting to delete with backgroun no-wait for $i${NC}"
rv=$(az group delete --resource-group $i --yes --verbose --no-wait)
else
echo -e "${RED}cannot delete $i now probably authorization${NC}"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment