Sometimes you would want to create an Azure ARM based Virtual Machine using an existing VHD disk. It used to be much easier in ASM (Classic). However you can easily swap out the OS disk for a VM using PowerShell. This post focuses on swapping un-managed disks, however you can swap out managed disks now, since April 2018.
Simply create a new (non-managed disk) based VM in Azure with new disks. Then you use PowerShell to swap out the OS disk with an existing disk. Good news is that the OS disk doesn’t have to be sysprepped, simply swap the VHD disk URI path using PowerShell, then fire back up the VM to get back into your existing VHD.
My example uses non-managed disks, remember with non-managed disks you have to manage a storage account, however with standard (non-premium(SSD)) non-managed disks, you are not charged for the white space on the disk. You could provision a 1TB disk with only 6KB of data and you are only charged for the data you consume. Plus it makes this process below work. Managed disks works slightly differently.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|# Recently tested fully with a later version of the Azure PowerShell module – Install-Module AzureRM -RequiredVersion 4.4.1|
|#region Logon to Azure|
|$subscription = Get-AzureRmSubscription | Out-GridView –PassThru|
|Select-AzureRmSubscription –SubscriptionId $subscription.Id|
|# Variables for YOu to fill in|
|$ResourceGroup = 'NestedVMware' # resource group name to contain the new NIC|
|$VMname = 'VMware-01' # name of the VM you want to swap out the OS disk|
|#Get the VM config to a variable|
|$VM = Get-AzureRmVM –Name $VMname –ResourceGroupName $ResourceGroup|
|#Stop and deallocate the VM|
|Stop-AzureRmVM –Name $VM.Name –ResourceGroupName $VM.ResourceGroupName –Force|
|#swap out the OS disk using the VM variable|
|$VM.StorageProfile.OsDisk.Vhd.Uri = 'https://storage5142161532.blob.core.windows.net/vhds/0120171108081251.vhd'|
|#Update the VM configuration|
|Update-AzureRmVM –VM $VM –ResourceGroupName $ResourceGroup|
If you are using managed disks, you can now swap out the managed disk of a VM as well by following this.
FYI, it seems that this is no longer allowed. Here is the error that I get when I follow this.
Update-AzureRmVM : Changing property ‘osDisk.vhd.uri’ is not allowed.
ErrorMessage: Changing property ‘osDisk.vhd.uri’ is not allowed.
Check the extension of the disk