Clone 30 VMs

#!/bin/bash
IMAGES_DIR="/home/saren/文件/raw-images/fast/test-win7"
TARGET_VM_COUNT=30

BASE_VM="win7-1"
BASE_IMAGE="${IMAGES_DIR}/win7-base-comp.qcow2"
TEMPLATE="win7-"

cd $IMAGES_DIR;

# Did not work
# SNAPSHOT_NAME="snapshot1"
# ss_template="/tmp/${TEMPLATE}ss.xml"
# sudo virsh snapshot-dumpxml --snapshotname ${SNAPSHOT_NAME} ${BASE_VM} > ${ss_template}

sudo qemu-img create -f qcow2 -b ${BASE_IMAGE} ${TEMPLATE}1.qcow2

for i in `seq 2 ${TARGET_VM_COUNT}`; do 

  vm=${TEMPLATE}${i}

  # Cleanup
  sudo virsh destroy ${vm}
  sudo virsh undefine ${vm} --snapshots-metadata

  # Create VM Images
  sudo qemu-img create -f qcow2 -b ${BASE_IMAGE} ${vm}.qcow2

  # Clone and define domains
  sudo virt-clone -f ${vm}.qcow2 -o ${BASE_VM} -n ${vm} --preserve-data;

  sudo virsh dumpxml ${vm} > /tmp/${vm}.xml
  c=$((2 + ${i}))
  t=$((38 + ${i}))
  echo "vcpu0: ${c}, vcpu1: ${t}"
  xmlstarlet ed \
    -u '/domain/cputune/vcpupin[@vcpu=0]/@cpuset' -v "${c}" \
    -u '/domain/cputune/vcpupin[@vcpu=1]/@cpuset' -v "${t}" \
    /tmp/${vm}.xml > /tmp/${vm}-pin.xml
  sudo virsh define /tmp/${vm}-pin.xml


  # Snapshots, did not work anyways
  : '
  # Clone images with reflink, so maybe btrfs only, but who the hell runs vm on btrfs?
  sudo cp -f --reflink=always ${BASE_VM}.qcow2 ${vm}.qcow2

  # But snapshots are not cloned, so need to let libvirt know there are snapshots too
  ss_template_i="/tmp/${TEMPLATE}ss-${i}.xml"
  # File paths need to be changed, IDs need to be correct
  xmlstarlet ed \
  -u '/domainsnapshot/domain/name' -v "${vm}" \
  -u '/domainsnapshot/domain/devices/disk[@device="disk"]/source/@file' -v "${IMAGES_DIR}/${vm}.qcow2" \
  -u '/domainsnapshot/domain/uuid' -v `sudo virsh domuuid ${vm} | xargs` \
  -u '/domainsnapshot/domain/devices/interface/mac/@address' -v `sudo virsh dumpxml ${vm} | xmlstarlet sel -t -v '/domain/devices/interface/mac/@address'` \
  ${ss_template} > ${ss_template_i}; 

  # Finally redefine the snapshot
  sudo virsh snapshot-create ${vm} --xmlfile ${ss_template_i} --redefine --current --reuse-external
  '

done

Recommendations

Last modified: 2019-01-16 17:15:42
Powered by Simple Blog