Importing and Exporting Virtual Machine Settings

I wanted to highlight the Export-AzureVM and Import-AzureVM cmdlets as I’ve seen quite a few recent cases where they come in handy when dealing with Windows Azure Virtual Machines.

Here are a few places where they can be exceptionally useful 🙂

Situation #1: Deleting a Virtual Machine when you are not using it and restoring it when you need it
Windows Azure billing charges for virtual machines whether they are booted or not. For situations where you have an “on and off” type of deployment such as development and test or even applications that don’t get as much usage after hours having the ability to save all of the current settings and remove and re-add later is huge.

Situation #2: Moving Virtual Machines between Deployments
If you ever find yourself in the situation where you need to remove and re-configure a VM in a different deployment. This could happen because you booted the VM up but placed it in the wrong cloud service or you misconfigured the virtual network and have to reconfigure.

There are likely many more scenarios but these seem to be the most common.

So here are a few examples to show how it works:

Exporting and Removing a Virtual Machine

# Exporting the settings to an XML file 
Export-AzureVM -ServiceName '<cloud service>'  -Name '<vm name>' -Path 'c:\vms\myvm.xml'
# Remove the Virtual Machine 
Remove-AzureVM -ServiceName '<cloud service>'  -Name '<vm name>'  

Note: Remove-AzureVM does not remove the VHDs for the virtual machines so you are not losing data when you remove the VM.

If you open up the xml file produced you will see that it is a serialized version of your VM settings including endpoints, subnets, data disks and cache settings.

At this point you could easily recreate the same virtual machine in a new or existing cloud service (specify -Location or -AffinityGroup to create a new cloud service). This operation could easily be split up into a few scheduled tasks to automate turning on and turning off your VMs in the cloud to save money when you aren’t using them.

Import-AzureVM -Path 'c:\vms\myvm.xml' | New-AzureVM -ServiceName '<cloud service>' -Location 'East US' 

For more than a single VM deployment PowerShell’s foreach comes to the rescue for some nice automation.

Exporting and Removing all of the VMs in a Cloud Service

Get-AzureVM -ServiceName '<cloud service>' | foreach { 
    $path = 'c:\vms\' + $_.Name + '.xml'
    Export-AzureVM -ServiceName '<cloud service>' -Name $_.Name -Path $path
# Faster way of removing all VMs while keeping the cloud service/DNS name 
Remove-AzureDeployment -ServiceName '<cloud service>' -Slot Production -Force 

Re-Importing all of the VMs to an existing Cloud Service

$vms = @()
Get-ChildItem 'c:\vms\' | foreach {
	$path = 'c:\vms\' + $_
	$vms += Import-AzureVM -Path $path
New-AzureVM -ServiceName '<cloud service>' -VMs $vms