Home > Enterprise >  Azure: Script or Command to delete instance and all its associated resources (disks, network interfa
Azure: Script or Command to delete instance and all its associated resources (disks, network interfa

Time:11-05

I am trying to find a way to delete an Instance in azure and all its associated resources. But I don't see any straightforward approach to accomplish it. I am using az vm delete -g resourcegroup -n myinstancename--yes command which currently only deletes instances. In my scenario, I can't use powershell.

CodePudding user response:

For testing ,I created a VM with 1 NIC, 1 Public IP and 2 Data disks.

enter image description here

Then, I used the below az CLI script :

$osDisk =  (az vm show --resource-group ansumantest --name ansumantest --query "storageProfile.osDisk.name" --output tsv)
$datadisks = (az vm show --resource-group ansumantest --name ansumantest --query "storageProfile.dataDisks[].name" --output tsv)
$nics= (az vm show --resource-group ansumantest --name ansumantest --query "networkProfile.networkInterfaces[].id" --output tsv)
foreach ($nic in $nics){
   $publicIps=az network nic show --id $nic --query "ipConfigurations[].publicIpAddress.id" --output tsv
}
az vm delete --resource-group ansumantest --name ansumantest --yes
if ($osDisk) { 
   az disk show --resource-group ansumantest --name $osDisk --yes
}
foreach ($datadisk in $Datadisks){
  az disk delete --resource-group ansumantest --name $datadisk --yes
}
foreach ($nic in $nics){
  az network nic delete --id $nic
}
foreach ($publicIp in $publicIps){
  az network public-ip delete --id $publicIp
}

Outputs:

enter image description here


OR

You can directly delete all the resources while the running the VM delete Command as well but there are some Prerequisites for this method i.e. While creating the VM using CLI you have to configure couple of features like below :

As per Microsoft Document in az vm create section:

  1. [--os-disk-delete-option {Delete, Detach}]

Specify the behavior of the managed disk when the VM gets deleted i.e whether the managed disk is deleted or detached. accepted values: Delete, Detach

  1. [--data-disk-delete-option]

Specify whether data disk should be deleted or detached upon VM deletion.

  1. [--nic-delete-option]

Specify what happens to the network interface when the VM is deleted. Use a singular value to apply on all resources, or use = to configure the delete behavior for individual resources. Possible options are Delete and Detach.

If the above 3 are configured to delete while creating the VM then , when you run the az vm delete it defaults to delete these resources when the VM is to be deleted.

Reference:

Github Support

  • Related