How can I delete tagged resources in a resource group while handling dependencies?
Asked by
MellowPine47
I'm writing a script to find resources in an Azure resource group, check their tag values, and delete only the resources matching a particular tag. The problem is that deletion order matters. For example, Azure won't allow a subnet to be deleted until all resources using it have been removed, so the script fails with a dependency error. The resources were originally deployed with Bicep, but I'm performing the cleanup through a custom script. How should I handle dependent resources when I can't rely on the loop order?
Answers
Another option is to group deletion logic by resource type. Delete resources that consume the network resources first, then delete network interfaces, virtual machines, and other attached objects, and handle subnets near the end. Keep the resource type-specific functions explicit rather than relying on the order returned by the resource-group query.
Reply to this answer
If youโre deleting resources with a custom script, youโll need to account for the dependency order yourself. First collect the candidate resources and show them for confirmation, then delete them in a known sequenceโfor example, workloads and network interfaces before subnets. Afterward, query the resource group again to confirm that everything expected was removed. Bicep created the dependency relationships, but it doesnโt automatically make an arbitrary deletion script dependency-aware.
MellowPine47: That makes sense. Everything was deployed with Bicep, but Iโm still using a script for the cleanup, so Iโll need to reproduce the relevant order there.
Reply to this answer
A retry approach can work if all dependent resources have the tag youโre targeting. Treat dependency failures as non-fatal, add those resources to a retry list, and make another pass after the first batch finishes. You can repeat this a limited number of timesโsay 5 to 10 passesโto handle chained dependencies without allowing the script to run forever. Anything still failing after that should be reported for manual review.
Reply to this answer
Add your answer
Answers are reviewed before publication.
BrightCedar6: Be careful with the tag filter, though: if a dependent resource is excluded because it lacks the tag, the parent resource may still be impossible to delete. The script should detect and report those dependencies instead of repeatedly retrying them.