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?
3 Answers
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.
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.
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.
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.

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.