0
votes

Let's say I have a resource group MyAppRG. It has a storage account, a SQL server, a keyvault, and a VM. How would I delete everything except the storage account and the keyvault in the resource group programmatically?

I know that there is a way to delete everything in a resource group by deploying an empty arm template deployment. I have tried using a Get-AzResource on the resources and adding it to the resources parameter to the ARM template, but it is not working. Something like this:

$storageAccounts = Get-AzStorageAccount -ResourceGroupName "MyAppRG" | Get-AzResource
$emptyArmTemplate = @{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  contentVersion: "1.0.0.0",
  "resources": @(storageAccounts),
}

New-AzResourceGroupDeployment -Name "test" -ResourceGroupName "MyAppRG" -TemplateObject $emptyArmTemplate -Force

But this does not work as the request is invalid.

1

1 Answers

1
votes

You could use tags to "filter out" the resources you wish to keep but the drawback to this approach is you will need to know what order to delete resources. For example, you will need to delete a web app before deleting the App Hosting Plan. In the example below I have a tag called 'DELETE' with a value of 'TRUE'.

get-AZresource -tagname delete -tagvalue true | Remove-AzResource

Honestly a better approach is to keep all the items you don't want deleted in a separate Resource Group and treat the RG has a lifecycle boundary. This way when you are ready to delete the unwanted items you can blow away the entire RG in one command.

Also if you are worried about someone accidently deleting certain resources, you should employ resource locks to add another check point before deletion.