#!/bin/sh # # Create a new VM for liw. set -eu verbose() { echo "INFO: $@" } die() { echo "$@" 1>&2 exit 1 } get_ip() { python -c ' import sys, json leases = json.load(open(sys.argv[1])) for lease in leases: if lease["mac-address"] == sys.argv[2]: print lease["ip-address"] ' "$1" "$2" } xz_uncompressed_size() { xz --robot --verbose --list "$1" | awk '/^file/ { print $5 }' } # Check parameters. if [ "$#" != 2 ] then die "Usage: $0 NAME BASE" fi # Config variables. . "$HOME/.config/ansibleness/vm.conf" # Command line parameters: name of VM and base image (no .img.xz suffix). name="$1" case "$2" in */*) basepath="$2" ;; *) basepath="$imagedir/base-$2.img.xz" ;; esac # Does the base image exist? if [ ! -e "$basepath" ] then echo "$basepath does not exist" 1>&2 exit 1 fi # How large is the (uncompressed) image? In bytes. size="$(xz_uncompressed_size "$basepath")" # Create new LV. sudo lvcreate --name "$name" --size "${size}b" \ --zero y --wipesignatures y --activate y "$vg" lvpath="/dev/$vg/$name" # Copy uncompressed image to LV. unxz < "$basepath" | pv --size "$size" | sudo ionice -c3 tee "$lvpath" > /dev/null # Create VM. virt-install --connect qemu:///system \ --quiet \ --name="$name" \ --memory=1024 \ --cpu=host-model-only \ --import \ --os-variant=debianwheezy \ --disk="path=$lvpath,cache=none" \ --network="$vmnetwork" \ --graphics=spice \ --noautoconsole # If we're using the virtual network "default", wait for the VM to get # a DHCP response and add it to /etc/hosts. We don't do it for other # types of network (e.g., bridge=br0), since we ... can't. if [ "$vmnetwork" = "network=default" ] then # Get the MAC address. mac="$(virsh -c qemu:///system dumpxml "$name" | sed -n "/ /dev/null # Done. echo "Virtual machine $name ($ip) has been created and started." else echo "Virtual machine $name has been created and started, and may be ready soon." fi