There are times when you want to delete all the resources within a specific Azure Resource Group, but you do not want to delete the resource group. Sure, deleting the entire resource group might be easier, but at this time that’s not an option. You can use the az resource list
and az resource delete
commands together to get a list of all the resources in the resource group and then delete them one-by-one.
Here’s a simple set of bash commands that use the Azure CLI to get the list of resources in the resource group, and then loop through that list to delete them one by one.
resources="$(az resource list --resource-group "myResourceGroup" | grep id | awk -F \" '{print $4}')"
for id in $resources; do
az resource delete --resource-group "myResourceGroup" --ids "$id" --verbose
done
It’s worth noting that this will not delete the resources in any specific order. So if you need to detach disks, or delete certain resources first, then you may need to just run this script multiple times until all the resources you want to delete have been deleted.
Also, you can use the --query
option with the az resource list
command to further filter down the list of resources to be deleted if you need to. This helps to be more precise as to which resources get deleted for those instances where you want to more easily delete multiple resources from within a single resource group, but not all of them at this time.
Happy scripting!
Hey Chris,
I find an easier way is to have a ‘removeall.json’ ARM template like the one showed below and then deploy it to a resource group using the ‘complete’ deployment mode. It ends up being quicker too. As in:
az deployment group create –resource-group YOURRESOURCEGROUP –template-file removeall.json –mode complete
— removeall.json ARM Template —
{
“$schema”: “https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#”,
“contentVersion”: “1.0.0.0”,
“parameters”: { },
“variables”: { },
“resources”: [ ],
“outputs”: { }
}
Or you could just use jq:
az resource list -g $RESOURCE_GROUP | jq -r ‘.[].id’
Beats having to filter those pesky empty lines…