Skip to content

Instantly share code, notes, and snippets.

@monester
Created February 15, 2018 11:02
Show Gist options
  • Save monester/56734f6ab34a3a616837a5cfb293fb08 to your computer and use it in GitHub Desktop.
Save monester/56734f6ab34a3a616837a5cfb293fb08 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -x
set -e
if [[ $(id -u) != 0 ]]; then
sudo $(realpath $0) $@
exit
fi
VIRSH='virsh --connect qemu:///system'
CLONE='virt-clone --connect=qemu:///system'
IMAGES_DIR="/home/libvirt/images"
ACTION=$(basename $(realpath $0))
VMNAME=$1
case "${ACTION}" in
"run")
test -n "${VMNAME}"
${CLONE} --original template --name "${VMNAME}" --file "${IMAGES_DIR}/${VMNAME}.img"
for i in `seq 2 100`; do
if ! ${VIRSH} net-dhcp-leases local | grep "192\.168\.99\.$i"; then
IP="192.168.99.$i"
break
fi
done
MAC=$(${VIRSH} dumpxml "${VMNAME}" | grep "mac address" |sed "s/.*mac address='\(.*\)'\/>/\\1/")
${VIRSH} net-update local add ip-dhcp-host "<host mac='${MAC}' name='${VMNAME}' ip='${IP}'/>" --live --config
echo "${IP} ${VMNAME}" | sudo tee -a /etc/hosts
${VIRSH} start "${VMNAME}"
;;
"rmvm")
test -n "${VMNAME}"
MAC=$(${VIRSH} dumpxml "${VMNAME}" | grep "mac address" |sed "s/.*mac address='\(.*\)'\/>/\\1/")
sudo sed -i "/ ${VMNAME}\$/d" /etc/hosts
${VIRSH} net-update local delete ip-dhcp-host "<host mac='${MAC}' name='${VMNAME}'/>" --live || true
${VIRSH} net-update local delete ip-dhcp-host "<host mac='${MAC}' name='${VMNAME}'/>" --config || true
${VIRSH} destroy "${VMNAME}" || true
${VIRSH} undefine "${VMNAME}" --remove-all-storage
;;
"rerun")
test -n "${VMNAME}"
BASEDIR=$(dirname $(realpath $0))
${BASEDIR}/rmvm "${VMNAME}"
${BASEDIR}/run "${VMNAME}"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment