0

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.

Hydromast
  • 280
  • 3
  • 10

1 Answers1

1

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.

Ken W - Zero Networks
  • 3,533
  • 1
  • 13
  • 18
  • I'd like to do the latter, but with how our environment is setup, it would be difficult. This is for our dev sandbox and in each of our resource group, we have RBACs dependency where we have to call our admin to setup, e.g Data Factories need read/write permission to the storage account. I think we do have to use Remove-AzResource after all, which is what I was trying to avoid since there's dependencies like you stated in your answer. Thank you! – Hydromast May 25 '21 at 22:15