DEV Community

Guilherme Mazzariol
Guilherme Mazzariol

Posted on

GCP - Copying VMs between projects

These days at work, I had to move some virtual machines (VM's) between different projects.
After doing a quick search and spending some time, this was the result.
Hope this helps you too.

Before you begin


How to copy VM with single boot disk

  1. Create a snapshot of persistent disk:

    gcloud compute snapshots SRC_SNAPSHOT_NAME \
        --source-disk SRC_DISK_NAME \
        --source-disk-zone ZONE \
        --project SRC_PROJECT
    
  2. Create a disk image from snapshot:

    gcloud compute snapshots SRC_SNAPSHOT_NAME \
        --source-disk SRC_DISK_NAME \
        --source-disk-zone ZONE \
        --project SRC_PROJECT
    
  3. Create the virtual machine:

    gcloud compute instances create DST_VM_NAME \
        --image-project SRC_PROJECT \
        --image SRC_IMG_NAME \
        --project DST_PROJECT
    

How to copy VM with boot disk and, at least one, attach disk

  1. Create snapshots from persistent disks:

    gcloud compute disks snapshot BOOT_DISK_NAME DATA_DISK_NAME \
        --snapshot-names SRC_SNAPSHOT_NAME_BOOT,SRC_SNAPSHOT_NAME_DATA \
        --zone ZONE \
        --project SRC_PROJECT`
    
  2. Create the disk image from boot snapshot:

    gcloud compute images create SRC_IMG_NAME_BOOT \
        --source-snapshot=SRC_SNAPSHOT_NAME_BOOT \
        --storage-location=ZONE \
        --project=SRC_PROJECT
    
  3. Create the disk image from data snapshot:

    gcloud compute images create SRC_IMG_NAME_DATA \
        --source-snapshot=SRC_SNAPSHOT_NAME_DATA \
        --storage-location=ZONE \
        --project=SRC_PROJECT
    
  4. Create the virtual machine using boot disk image:

    gcloud compute instances create DST_VM_NAME \
        --image-project SRC_PROJECT \
        --image SRC_IMG_NAME_BOOT \
        --project=DST_PROJECT
    
  5. Create persistent disk from data disk image:

    gcloud compute disks create DISK_NAME_DATA \
        --image-project SRC_PROJECT \
        --image SRC_IMG_NAME_DATA \
        --project=DST_PROJECT
    
  6. Attach data disk into the instance:

    gcloud compute instances attach-disk DST_VM_NAME \
        --disk DISK_NAME_DATA \
        --project=DST_PROJECT
    
  7. Mount the new disk:

    # connect to the instance
    gcloud compute ssh DST_VM_NAME --zone ZONE --project GCP_PROJECT
    # change to root user
    sudo su
    # indetify the new disk (probably will be 'sdb')
    lsblk
    # create new folder
    mkdir /FOLDER_NAME
    # mount the disk
    mount -o discard,defaults /dev/sdb /FOLDER_NAME
    # check files
    ls /FOLDER_NAME/
    # add write permission for all
    chmod a+w /FOLDER_NAME
    # create new entry to fstab
    echo UUID=`sudo blkid -s UUID -o value /dev/sdb` /FOLDER_NAME ext4 discard,defaults,nofail 0 2 | sudo tee -a /etc/fstab
    

Any questions or suggestions, please write to me :)

Top comments (0)