summaryrefslogtreecommitdiff
path: root/vm-libvirt.sh
blob: f7c07056995ad60f7114940c6457c55b32360b48 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/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 3 ]
then
    die "Usage: $0 NAME IMAGE WORKSPACEIMAGE [virt-install-options]"
fi
verbose "Command line args OK"


# Command line parameters: name of VM and image file.
name="$1"
image="$2"
workspace="$3"
verbose "creating VM $name from image $image, using $workspace as workspace"

shift 3

# 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 \
             --vcpus=4 \
             --cpu=host \
             --import \
             --os-variant=debian9 \
             --disk="path=$image,cache=none" \
             --disk="path=$workspace,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

# Write ssh config file with VM info.
cat > "$HOME/.ssh/config-local" <<EOF
Host $name
    Hostname $ip
    UserKnownHostsFile /dev/null
    StrictHostKeyChecking no
EOF

# Done.
echo "Virtual machine $name ($ip) has been created and started."