Last active
January 22, 2020 13:31
-
-
Save gpolitis/4e03909357b455e242d58109e075de47 to your computer and use it in GitHub Desktop.
A helper script to create xhyve virtual machines with cloud-init support.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Copyright (c) 2020 Georgios Politis | |
# Distributed under the MIT software license, see the accompanying | |
# file COPYING or http://www.opensource.org/licenses/mit-license.php. | |
XHYVE_HOME=${XHYVE_HOME:-"$HOME/Virtual Machines"} | |
oups () { | |
echo "$1" 1>&2 | |
exit 1 | |
} | |
usage () { | |
oups "Usage: $0 INSTANCE_NAME DISK_IMAGE [--vcpus=VCPUS] [--memory=MEMORY]" | |
} | |
if [ $# -lt 2 ] | |
then | |
usage | |
fi | |
INSTANCE_NAME="$1" | |
INSTANCE_HOME="$XHYVE_HOME/$INSTANCE_NAME" | |
if [ -d "$INSTANCE_HOME" ] | |
then | |
oups "The specified instance already exists." | |
fi | |
MACHINE_HOME="$2" | |
MACHINE_DISK="$MACHINE_HOME/disk.img" | |
MACHINE_VMLINUZ="$MACHINE_HOME/vmlinuz" | |
MACHINE_INITRD="$MACHINE_HOME/initrd" | |
if [ ! -f "$MACHINE_DISK" -o ! -f "$MACHINE_VMLINUZ" -o ! -f "$MACHINE_INITRD" ] | |
then | |
oups "The machine is not found." | |
fi | |
mkdir -p "$INSTANCE_HOME" | |
INSTANCE_SEED_DIR=`mktemp -d` | |
INSTANCE_SEED_ISO="$INSTANCE_HOME/seed.iso" | |
INSTANCE_METADATA="$INSTANCE_SEED_DIR/meta-data" | |
INSTANCE_USERDATA="$INSTANCE_SEED_DIR/user-data" | |
cat << EOF > $INSTANCE_USERDATA | |
#cloud-config | |
ssh_authorized_keys: | |
- `cat $HOME/.ssh/id_rsa.pub` | |
packages: | |
- python | |
- avahi-daemon | |
EOF | |
cat << EOF > "$INSTANCE_METADATA" | |
local-hostname: $INSTANCE_NAME | |
EOF | |
hdiutil makehybrid -o "$INSTANCE_SEED_ISO" -hfs -joliet -iso -default-volume-name cidata "$INSTANCE_SEED_DIR" | |
rm -rf "$INSTANCE_SEED_DIR" | |
INSTANCE_LAUNCH="$INSTANCE_HOME/xhyverun-instance.sh" | |
INSTANCE_DISK="$INSTANCE_HOME/disk.img" | |
INSTANCE_VMLINUZ="$INSTANCE_HOME/vmlinuz" | |
INSTANCE_INITRD="$INSTANCE_HOME/initrd" | |
INSTANCE_CPU=1 | |
INSTANCE_MEM=1G | |
qemu-img convert -O raw "$MACHINE_DISK" "$INSTANCE_DISK" | |
ln "$MACHINE_VMLINUZ" "$INSTANCE_VMLINUZ" | |
ln "$MACHINE_INITRD" "$INSTANCE_INITRD" | |
cat << EOF > "$INSTANCE_LAUNCH" | |
#!/bin/sh | |
exec xhyve \\ | |
-A \\ | |
-c $INSTANCE_CPU \\ | |
-m $INSTANCE_MEM \\ | |
-s 0:0,hostbridge \\ | |
-s 2,virtio-net \\ | |
-s 3:0,ahci-cd,"$INSTANCE_SEED_ISO" \\ | |
-s 4,virtio-blk,"$INSTANCE_DISK" \\ | |
-s 31,lpc \\ | |
-l com1,stdio \\ | |
-f "kexec,$INSTANCE_VMLINUZ,$INSTANCE_INITRD,earlyprintk=serial console=ttyS0 root=/dev/vda1 ro" | |
EOF | |
chmod +x "$INSTANCE_LAUNCH" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment