AzureStack Delete All the resources and their dependent resources in a Resource Group

818 Views Asked by At

I am writing an script that would get all the resources in a resource group and removed them and then it removes the resource group itself in an azurestack environment. I couldn't just use

$Resources = Find-AzureRmResource -ResourceGroupName $ResourceGroupName

foreach ($resource in $Resources)
{
    Remove-AzureRmResource -ResourceGroupName $ResourceGroupName -ResourceName $resource .Name -ResourceType $resource.ResourceType -Force
}

because if I have Offers in my resource group and that offer has subscriptions in it, then I cannot remove the Offer before removing the all the subscriptions in it. My Question is: is there a way to get each resource $A in a resource group $RG and all the dependent resources $D for that resource $A and delete them?

There can be so many types of resources in a resource group, and I am not sure what are the other resources beside "offers" that could have dependent items which would have to be removed first before the resource can be removed. for example, what if my resource group has Virtual machines in it, is there network adapters that need to be removed first?

what is the hierarchy for removing resources in a resource group and how are they depended on each other.( I wish there was a dependents attribute for each resource in Azurestack so you could see what are the things that needs to be removed in order to be able to remove that item.

2

There are 2 best solutions below

0
On

5 months old, but this may help someone else. If the intention is to remove the resources associated with a RG, then a way is to ask ARM to deploy a no-resource template in your current RG(which has resources) in "complete" deployment option. In the "complete" option, whatever resource mentioned in the template will be deployed and resources not mentioned in the template will be deleted (on existing RG). So if no resource is specified in the template, the resources should get deleted with proper dependency and parallelism benefits given by ARM

0
On

You can also see how the ARM decides the dependencies while deleting - if you want to delete them one by one

https://learn.microsoft.com/ga-ie/azure/azure-resource-manager/resource-group-delete?view=azurermps-6.10.0

========= When you delete a resource group, Resource Manager determines the order to delete resources. It uses the following order:

All the child (nested) resources are deleted.

Resources that manage other resources are deleted next. A resource can have the managedBy property set to indicate that a different resource manages it. When this property is set, the resource that manages the other resource is deleted before the other resources.

The remaining resources are deleted after the previous two categories