Change the OS disk used by an Azure VM using the Azure CLI

Applies to: ✔️ Linux VMs ✔️ Flexible scale sets

If you have an existing VM, but you want to swap the disk for a backup disk or another OS disk, you can use the Azure CLI to swap the OS disks. You don't have to delete and recreate the VM. You can even use a managed disk in another resource group, as long as it isn't already in use.

The VM does not need to be stopped\deallocated. The resource ID of the managed disk can be replaced with the resource ID of a different managed disk.

Make sure that the VM size and storage type are compatible with the disk you want to attach. For example, if the disk you want to use is in Premium Storage, then the VM needs to be capable of Premium Storage (like a DS-series size). Both disks must also be the same size. And ensure that you're not mixing an un-encrypted VM with an encrypted OS disk, this is not supported. If the VM doesn't use Azure Disk Encryption, then the OS disk being swapped in shouldn't be using Azure Disk Encryption. If disks are using Disk Encryption Sets, both disks should belong to same Disk Encryption set.

This article requires Azure CLI version 2.0.25 or greater. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI.

Use az disk list to get a list of the disks in your resource group.

az disk list \
   -g myResourceGroupDisk \
   --query '[*].{diskId:id}' \
   --output table

(Optional) Use az vm stop to stop\deallocate the VM before swapping the disks.

az vm stop \
   -n myVM \
   -g myResourceGroup

Use az vm update with the full resource ID of the new disk for the --osdisk parameter

az vm update \
   -g myResourceGroup \
   -n myVM \
   --os-disk /subscriptions/<subscription ID>/resourceGroups/<resource group>/providers/Microsoft.Compute/disks/myDisk 

Restart the VM using az vm start.

az vm start \
   -n myVM \
   -g myResourceGroup

Next steps

To create a copy of a disk, see Snapshot a disk.