how to delete relevant resources when deleting a virtual machine

Viewed 390

I am using Azure CLI version 2.34.1. I ran following commands to create a resource group and then a virtual machine. Note that I used options to delete relevant resources when the VM is deleted.

az group create --name myTestRG --location eastus
az vm create --resource-group myTestRG --name myTestWindows11VM --image MicrosoftWindowsDesktop:windows-11:win11-21h2-pro:22000.493.220201 --admin-username someusername --os-disk-delete-option delete --nic-delete-option delete

Later I deleted the VM using following command.

az vm delete --name MyTestWin11VM --resource-group myTestRG -y 

However, when I browse to the portal, the resource group still showing following resources that are relevant to the VM. enter image description here

What I may be doing wrong? Is there anyway to delete all resources associated to VM when I delete the virtual machine itself?

1 Answers

UPDATE ITS A BUG:

enter image description here


The way Azure works is to group resources in Resource Groups - its a mandatory field in all creation of services. Azure does this because many resources have dependencies, such as a VM with a NIC, VNet & NSG.

You can use this to your advantage and simply delete the Resource Group:

az group delete --name myTestRG 

Azure will work out the dependency order, eg NSG, VNet, NIC, VM. You can read up on how it does the ordering: https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/delete-resource-group?tabs=azure-cli

What happens if I have multiple VMs in a Resource Group and I only want to delete one?

There's 3 new options --os-disk-delete-option, --data-disk-delete-option, --nic-delete-option to support deleting VMs and dependencies:

az vm create \
    --resource-group myResourceGroup \
    --name myVM \
    --image UbuntuLTS \
    --public-ip-sku Standard \
    --nic-delete-option delete \
    --os-disk-delete-option delete \
    --admin-username azureuser \
    --generate-ssh-keys

Otherwise script the whole thing using Azure Resource Manager Templates (ARM Templates), or the new tool to generate ARM Templates called Bicep. It's worth continuing with raw CLI commands and delete dependencies in order. IF you get good with the CLI you end up with a library of commands that you can use with ARM templates.

Related