Remove Azure Deployments, Not the Resource Group – Part 2
A previous blog of mine showed how to remove a resource group by deployment. Since then Azure has changed quite a bit, such as managed disks.
Recently while working on a CI/CD pipeline, I noticed that we were building a lot of jobs, sometimes with many Virtual Machines (VM). And you guessed it, when we were done testing we wanted a fast way to clean up our resource groups after ourselves.
I wrote a script that would take the deployment, break it down and reverse how it was deployed, then delete it. At first the function worked great. But we noticed it was taking hours to destroy a 12-node cluster. I went back to the function and added in a workflow to remove the VM’s in parallel. The result is a normal deployment should now remove itself in under 7 minutes! Excellent, so now let’s implement this.
You want to remove a deployment, but first let’s create a SPN. We do this for a few reasons. One, we want a way to pass in the credentials to our workflow, due to the workflow spawning each VM’s removal in its own process. Because of this, each process has to be able to sign in. And two, we want to make this re-usable in a CI/CD System, meaning we don’t want to pass in our own credentials. In this case we make a job in Jenkins to pass in all the variables. If you don’t have a SPN, you can use Microsoft walk through for this. To make it easy, we gave our SPN Contributor access at the resource group level.
Once you have your SPN created and assigned the correct RBAC permissions, head over and download the function here.
Next, instantiate the script from a PowerShell command.
cd <path to the function>
Finally you can now remove the deployment by running the following line:
Remove-Deployment -deploymentname “deploymentnmae” -resourcegroup “rgname” -subscriptionId “subid” -applicationid “appid with contributor right” -applicationkey “app key” -tenantid “tenantid”