summaryrefslogtreecommitdiff
path: root/create-vm
blob: 57d3206893ca8b4c428206e62235eb20b2f1b541 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/bin/sh
#
# Create a new VM for liw.


set -eu


die()
{
    echo "$@" 1>&2
    exit 1
}


# Check parameters.

if [ "$#" != 2 ]
then
    die "Usage: $0 NAME BASE"
fi


# Command line parameters: name of VM and base image (no .img.xz suffix).
name="$1"
base="$2"

# Config variables.
. "$HOME/.config/ansibleness/vm.conf"

# Does the base image exist?
basepath="$imagedir/base-$base.img.xz"
if [ ! -e "$basepath" ]
then
    echo "$basepath does not exist" 1>&2
    exit 1
fi

# How large are the (uncompressed) images?
size="4G"

# Create new LV.
sudo lvcreate --name "$name" --size "$size" "$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 "/<mac address=/s/^.*'\(.*\)'.*/\1/p")"

    # Get IP address related to the MAC address. Append that to /etc/hosts.
    leases=/var/lib/libvirt/dnsmasq/default.leases
    ip=""
    while [ "$ip" = "" ]
    do
        sleep 1
        ip="$(awk -v "mac=$mac" '$2 == mac { print $3 }' "$leases")"
    done
    echo "$ip $name" | sudo tee -a /etc/hosts > /dev/null

    # Done.
    echo "Virtual machine $name ($ip) has been created and started."
else
    echo "Virtual machien $name has been created and started, and may be ready soon."
fi