summaryrefslogtreecommitdiff
path: root/vm-libvirt.sh
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2020-04-01 10:13:00 +0300
committerLars Wirzenius <liw@liw.fi>2020-04-01 10:13:00 +0300
commitac88fa50e815fa6e96decd254a2e3b86bb8d749d (patch)
tree081769ad61010e19c2a8ab0f596a479cf7c80844 /vm-libvirt.sh
parentec077cfc91e4f1220fdbce53c8bd2f10b402fe50 (diff)
downloadick-contractor-ac88fa50e815fa6e96decd254a2e3b86bb8d749d.tar.gz
Add: script to start a VM via libvirt
Diffstat (limited to 'vm-libvirt.sh')
-rwxr-xr-xvm-libvirt.sh105
1 files changed, 105 insertions, 0 deletions
diff --git a/vm-libvirt.sh b/vm-libvirt.sh
new file mode 100755
index 0000000..c5788af
--- /dev/null
+++ b/vm-libvirt.sh
@@ -0,0 +1,105 @@
+#!/bin/sh
+#
+# Create a new VM using libvirt on the local host.
+
+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" || true
+}
+
+
+xz_uncompressed_size()
+{
+ xz --robot --verbose --list "$1" | awk '/^file/ { print $5 }'
+}
+
+raw_uncompressed_size()
+{
+ stat -c %s "$1"
+}
+
+
+# Check parameters.
+
+if [ "$#" -lt 2 ]
+then
+ die "Usage: $0 NAME IMAGE [virt-install-options]"
+fi
+verbose "Command line args OK"
+
+
+# Command line parameters: name of VM and image file.
+name="$1"
+image="$2"
+verbose "creating VM $name from image $image"
+
+shift 2
+
+# Does the image exist?
+if [ ! -e "$image" ]
+then
+ echo "$image does not exist" 1>&2
+ exit 1
+fi
+verbose "$image exists"
+
+
+# Create VM.
+verbose "Creating VM"
+virt-install --connect qemu:///system \
+ --quiet \
+ --name="$name" \
+ --memory=8192 \
+ --cpu=host-model-only \
+ --import \
+ --os-variant=debian9 \
+ --disk="path=$image,cache=none" \
+ --network="network=default" \
+ --graphics=spice \
+ --noautoconsole \
+ "$@"
+
+# Wait for the VM to get a DHCP response and add it to /etc/hosts.
+verbose "Waiting for VM to boot to gets its MAC"
+
+mac="$(virsh -c qemu:///system dumpxml "$name" |
+ sed -n "/<mac address=/s/^.*'\(.*\)'.*/\1/p")"
+verbose "MAC: $mac"
+
+# Wait for libvirt's DHCP server to give the VM an IP.
+verbose "Waiting for VM to get its IP"
+ip=""
+leases=/var/lib/libvirt/dnsmasq/virbr0.status
+while [ "$ip" = "" ]
+do
+ sleep 1
+ if [ -s "$leases" ]
+ then
+ ip="$(get_ip "$leases" "$mac")"
+ fi
+done
+
+# Done.
+echo "Virtual machine $name ($ip) has been created and started."