Skip to content

Instantly share code, notes, and snippets.

@IridiumXOR
Forked from aojea/linked-clone.sh
Created August 20, 2024 15:42
Show Gist options
  • Save IridiumXOR/a2936a39963aa58000a68b628fd979c3 to your computer and use it in GitHub Desktop.
Save IridiumXOR/a2936a39963aa58000a68b628fd979c3 to your computer and use it in GitHub Desktop.

Revisions

  1. @aojea aojea revised this gist Aug 16, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion linked-clone.sh
    Original file line number Diff line number Diff line change
    @@ -33,7 +33,7 @@ chmod a-w $VM_NAME.qcow2
    virsh --connect=qemu:///system dumpxml $VM_NAME > /tmp/golden-vm.xml

    # Create a linked clone in the current folder
    qemu-img create -f qcow2 -b $VM_NAME.qcow2 $VM_CLONE.qcow2
    qemu-img create -f qcow2 -o backing_fmt=qcow2 -b $VM_NAME.qcow2 $VM_CLONE.qcow2

    # hardware addresses need to be removed, libvirt will assign
    # new addresses automatically
  2. Antonio Ojea created this gist Oct 5, 2017.
    47 changes: 47 additions & 0 deletions linked-clone.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    #!/bin/bash

    set -xe
    # This script takes as a parameter the name of the VM
    # and creates a linked clone
    # Ref: https://unix.stackexchange.com/a/33584
    # The scripts assumes that it runs from the same folder
    # where the vm image is located and it coincides with the
    # image name

    # if less than two arguments supplied, display usage
    if [ $# -ne 2 ]
    then
    echo "This script takes as input the name of the VM to clone"
    echo "Usage: $0 vm_name_orig vm_name_clone"
    exit 1
    fi

    VM_NAME=$1
    VM_CLONE=$2

    # You cannot "clone" a running vm, stop it. suspend and destroy
    # are also valid options for less graceful cloning
    if virsh --connect=qemu:///system list | grep $VM_NAME
    then
    virsh --connect=qemu:///system shutdown $VM_NAME
    sleep 60
    fi
    # Make the golden image read only
    chmod a-w $VM_NAME.qcow2

    # dump the xml for the original
    virsh --connect=qemu:///system dumpxml $VM_NAME > /tmp/golden-vm.xml

    # Create a linked clone in the current folder
    qemu-img create -f qcow2 -b $VM_NAME.qcow2 $VM_CLONE.qcow2

    # hardware addresses need to be removed, libvirt will assign
    # new addresses automatically
    sed -i /uuid/d /tmp/golden-vm.xml
    sed -i '/mac address/d' /tmp/golden-vm.xml

    # and actually rename the vm: (this also updates the storage path)
    sed -i s/$VM_NAME/$VM_CLONE/ /tmp/golden-vm.xml

    # finally, create the new vm
    virsh --connect=qemu:///system define /tmp/golden-vm.xml