Create a virtual machine using an existing managed OS disk with CLI

This script creates a virtual machine by attaching an existing managed disk as OS disk. Use this script in preceding scenarios:

  • Create a VM from an existing managed OS disk that was copied from a managed disk in different subscription
  • Create a VM from an existing managed disk that was created from a specialized VHD file
  • Create a VM from an existing managed OS disk that was created from a snapshot

To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with Azure.

Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command Prompt, you may need to change elements of the script.

If you don't have an Azure subscription, create a free account before you begin.

Sample script

#Provide the subscription Id

#Provide the name of your resource group

#Provide the name of the Managed Disk

#Provide the OS type

#Provide the name of the virtual machine

#Set the context to the subscription Id where Managed Disk exists and where VM will be created
az account set --subscription $subscriptionId

#Get the resource Id of the managed disk
managedDiskId=$(az disk show --name $managedDiskName --resource-group $resourceGroupName --query [id] -o tsv)

#Create VM by attaching existing managed disks as OS
az vm create --name $virtualMachineName --resource-group $resourceGroupName --attach-os-disk $managedDiskId --os-type $osType

Clean up deployment

Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup

Script explanation

This script uses the following commands to get managed disk properties, attach a managed disk to a new VM and create a VM. Each item in the table links to command specific documentation.

Command Notes
az disk show Gets managed disk properties using disk name and resource group name. Id property is used to attach a managed disk to a new VM
az vm create Creates a VM using a managed OS disk

Next steps

For more information on the Azure CLI, see Azure CLI documentation.

Additional virtual machine CLI script samples can be found in the Azure Linux VM documentation.