Copy Data disk from one Azure virtual machine to another

Consider a case where you have configured an Azure virtual machine that hosts applications and you have saved an application data in multiple data disks. Now you want to create multiple virtual machines or copy all those data disks to other virtual machines.

Use the below code to copy data disks from one virtual machine to another machine. Source and destination virtual machines must be in same Resource Group.

1. Create a temporary Snapshot of Data disk

2. Create Managed disk from Snapshot created in Step 1

3. Attach the Managed disk (created from Step 2) to the destination Azure virtual machine

4. Update the destination Azure virtual machine with the new Managed disks

5. Delete the temporary Snapshots

PowerShell:
## Create temporary Snapshot from a Managed Disk ## 
 
$resourceGroupName = 'copy_disk' # Source and Destination has to be in same Resource Group 
$location = 'east us 2' # Source and Destination has to be in same location 
$source_vm_name = 'server1'# Name of source virtual machine 
$destination_vm_name = 'server3' # Name of destination virtual machine 
$storageType = 'StandardLRS' # Type of managed disk 
 
 
$source_vm_object = get-azurermvm -ResourceGroupName $resourceGroupName -Name $source_vm_name 
 
$data_disk_list = Get-AzureRmDisk | where {$_.ManagedBy -match $source_vm_name -and $_.OsType -eq $null} 
 
$snapshot_list = New-Object System.Collections.ArrayList($null$snapshot_list_name = New-Object System.Collections.ArrayList($null) 
 
foreach($data_disk_list_iterator in $data_disk_list){ 
     
    $snapshotName = $destination_vm_name + "_Snapshot_" + $data_disk_list_iterator.Name 
 
    $snapshot_config = New-AzureRmSnapshotConfig -SourceUri $data_disk_list_iterator.id -Location $location -CreateOption copy 
 
    $snapshot_object = New-AzureRmSnapshot -Snapshot $snapshot_config -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName 
 
    $snapshot_list.Add($snapshot_object.Id) 
 
    $snapshot_list_name.Add($snapshot_object.Name) 
} 

Be the first to comment

Leave a Reply

Your email address will not be published.


*