Monday 18 May 2020

Create an Azure VM with Existing Disk,Network and Hostname with PowerShell

Hello,

In Azure, if you are deleting a VM instance it just deletes the VM object and would keep the Disk(s) and Network(s) intact.

There is a feature request to enable cleanup of this lingering objects.
https://feedback.azure.com/forums/216843-virtual-machines/suggestions/8945692-delete-vm-with-all-associated-resources?page=1&per_page=20

So this is good in one way and bad in another.
Good - accidental deletions - you have backup but still we have the fastest way to bring the VM up by re-creating it.
Bad - actual deletions and additional cleanup.

Lets do this..

Assume we deleted a VM instance "Webserver01" and have no details about the Properties of the VM saved.

We build the Properties of the VM and create it.

What the webserver01 has.
1. One Network Interface, with a private and public IP
2. One OS disk.

Remove the 'webserver01'  with Powershell.



 If you search in the portal for the hostname delete you would still see the attached disk and network.





How do we get the details of the deleted VM size?
The Resourge Group -> Deployments Tab would hold the deployment information.
This tab gives us the details we need for this activity. Indeed it has more details.






 We got the VM Size, basically we can check the deployment operation to get the other details.

$recreateVM = New-AzVMConfig -VMName "webserver01" -VMSize "Standard_B2s"
Populating the variable $recreateVM



Attaching the existing disk.

Get the below details from the disk inventory.



Since i am re-creating a windows machine i would specify at the end of the command.

Set-AzVMOSDisk -VM $recreateVM -CreateOption Attach -ManagedDiskId "<replace with ResourceID>" -Name "<replace with Disk name>" -Windows
 Populating the variable $recreateVM


Fetching the network information.



Populating the requirements.


Finally re-creating the VM.

New-AzVM -ResourceGroupName rg-eastus2 -Location eastus2 -VM $recreateVM



VM status.




The process gets a little complex than this when we have additiona storage disks and multiple NICs and an Avalibility Set to place the VM.

Happy Scripting.