Remove all resources within a Resource Group with Azure DevOps and ARM

post-thumb

Did you know it’s quite easy to remove all resources within a Resource Group via an ARM template. Sometimes you just need to “empty” a Resource Group without removing the Resource Group itself.

This way settings like Access Control and tags which are configured on the Resource Group itself will not be removed. You can also login to the Azure Portal, select all the resources within a Resource Group and click “Delete“, probably you will find yourself deleting depended resources first before you can delete the last bits of your previous deployment. So why not automate this!

What you basically do is deploying an empty ARM template to the resource group in complete mode. In complete mode, the Resource Manager deletes resources that exist in the resource group but aren’t specified in the template.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-08-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "variables": {},
  "resources": [],
  "outputs": {}
}

You can copy the above ARM template or download it from my GitHub repository .

There are multiple ways of deploying this ARM template, in this post I will describe how to deploy it via an Azure DevOps pipeline.

Azure DevOps

First upload the .json file to your Azure DevOps repository, and make sure the file is available during your build or release pipeline. In this demo I will use a release pipeline to empty the Resource Group before deploying new resources.

Create a new stage, and add a new task to the agent job. This pipeline will use the Artifacts created in the build pipeline.

Azure DevOps – Release pipeline

Open up the stage and add the ARM template deployment task to the agent. This task will deploy the ARM template in Complete mode to the selected Resource Group.

Azure DevOps – Agent job
Now we are ready to start this task. At this moment the Resource Group contains 3 WVD Session Hosts with multiple Availability sets.

Azure Portal – Resource Group
Create a new release and watch the magic happens. The pipeline is first going to download the artifacts and then deploy the ARM template and thus removing the resources within in the configured Resource Group.

Azure DevOps – New Release
You can navigate to the Resource Group and check the status of the deployment in Settings –> Deployments.

Azure Portal – Deployment

After a few minutes the release pipeline will be completed and the resources within the Resource Group will be removed. In this case after 2 minutes and 1 second.

Azure Portal – Deployment complete

That’s it, thanks to my colleague Jordi van Drunen I now have the possibility to empty a Resource Group. You can for example use this before deploying a VM which will be used to create a Golden Image. After the VM has been captured you can cleanup the created resources.

comments powered by Disqus