Windows Virtual Desktop – Reusing your template VM

When working with Windows Virtual Desktop and custom images, you will notice that you need to sysprep your master image that makes it useless for the rest of the time. In my previous post I advised to create a pre-sysprep snapshot so we can re-use the same image without too much hassle.

In this post, I’ll explain how to revert your VM back to the pre-sysprep snapshot easily and without deleting the VM or any of the other configuration for it. To help us, we are going to make use of the “Swap OS disk” feature in Azure.

While you could technically perform half of the steps in the Azure portal using the Swap OS disk on the VM disks blade, this post will go fully into PowerShell as it would probably be easier to use that:

First, we load all the variables:

$diskName = 'MyNewDisk' #The name for the new disk
$myVM='TemplateVM' #The name of the template VM
$resourcegroup='TemplateResourceGroup' #The name for the resource group of the VM
$snapname='PreSysPrepSnapshot' #The original snapshot (should be in VM resgroup)

Next, we will get the VM and original OS disk properties:

#Get the VM and Disk properties
$vm=get-azvm -ResourceGroupName $resourcegroup -Name $myVM
$originaldisk=get-azdisk -name $vm.StorageProfile.OsDisk.name
$storageType=$originaldisk.Sku.Name
$diskSize=$vm.StorageProfile.OsDisk.DiskSizeGB
if (!($disksize)){ $diskSize=127}

This ensures that we have the VM, and the original OS disk size and SKU available to use later-on, so our new OS disk will use the same properties.

#Making a managed disk from the snapshot
$snapshot = Get-AzSnapshot -ResourceGroupName $resourcegroup -SnapshotName $snapname
$diskConfig = New-AzDiskConfig -SkuName $storageType -Location $vm.Location -CreateOption Copy -SourceResourceId $snapshot.Id -DiskSizeGB $diskSize
$disk=New-AzDisk -Disk $diskConfig -ResourceGroupName $originaldisk.ResourceGroupName -DiskName $diskName

This part creates a new (managed) disk from the earlier created snapshot (in my previous post). It also ensures that the storagetype is the same as for the one used in the original OS disk. The new OS disk will be created in the same ResourceGroup as the Original OS disk. Which means we can now update the VM:

#Switch the OS disk on the VM
Set-AzVMOSDisk -VM $vm -ManagedDiskId $disk.Id -Name $disk.Name
Update-AzVM -ResourceGroupName $resourcegroup -VM $vm

We switch the OS disk on the VM configuration and update it. The VM will be rebooted after issuing this command to load the OS from the newly created disk, that was created from your earlier snapshot.

Now you can continue to update your golden master image (installing applications and such..) then create a new snapshot, sysprep the image, snapshot it again, export the snapshot for WVD, revert the OS disk to pre-sysprep snapshot and on and on and on

And that’s it!

Tagged ,