Sunday, January 1, 2017

Duplicating an Azure ARM VM

On Azure classic deployments, duplicating an Azure VM due to QA/R&D needs was easily done via the portal using the capture image option and later creating a VM from that image.
Unfortunately on ARM deployments this option is not available, so the course of action to create such a duplicate, is to use Powershell scripts.
In the below example, I deploy to an existing resource group and virtual network, but the scripts can be easily altered to create those as well if needed.

For the first step, I shutdown the VM I wanted to duplicate and copied its OS disk to a new storage/blob container (same blob container can be used, just need to rename the disk). To copy the disk I used Azure storage explorer.

And now for the Powershell scripts.


#Log into Azure account and select the proper subscription.
Add-AzureRmAccount            
Select-AzureRmSubscription -SubscriptionName mysubscription

#Set parameters such as resource group name, VNET name and region.
$rgname = "myresourcegroup"
$location = "West Europe"
$vnet = "myVNET"

#Create a network interface for the VM (replace xxx... with the subscription ID, replace subnet1 with the actual subnet name)
$nic = New-AzureRmNetworkInterface -Name mynic -ResourceGroupName $rgname -Location $location -SubnetId "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/$rgname/providers/Microsoft.Network/virtualNetworks/$vnet/subnets/Subnet1"

#Create a network security group
$nsg = New-AzureRmNetworkSecurityGroup -ResourceGroupName $rgName -Location $location -Name mynsg

#Set OS disk  parameter that points to the disk copy from which the VM will be created
$OSVhdUri = "https://mystorage01.blob.core.windows.net/vhds/mydisk.vhd"

#Parameter for VM name
$vmName = "MYDUPLICATEVM"

#VM configuration parameters such as VM size and network and OS disk name
$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize "Standard_A2"
$vm = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $nic
$OSDiskName = $vmName + "OSDisk"

#Setting duplicated disk as OS disk
$vm = Set-AzureRmVMOSDisk -VM $vmConfig -Name $OSDiskName -VhdUri $OSVhdUri -CreateOption attach -Windows

#Creating the new VM
New-AzureRmVM -ResourceGroupName $rgname -Location $location -VM $vm


If needed a public IP can be created and attached to the network interface either via the Azure portal or via Powershell.


Note: MS doesn't officially support duplicated VMs that were not generalized with Sysprep.



No comments:

Post a Comment