Skip to content

Instantly share code, notes, and snippets.

@joerx
Last active December 13, 2022 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joerx/17bec531c964400e1f71dfa87a5d511e to your computer and use it in GitHub Desktop.
Save joerx/17bec531c964400e1f71dfa87a5d511e to your computer and use it in GitHub Desktop.

Minimalistic Development Box with Libvirt

Linux only, requires KVM and QEMU. libvirt and related components need to be installed. Provisions a development VM based on Ubuntu 20.04. Current working directory will be shared with the guest. This is a PoC, not intended to be a fully functional tool. For any serious use case, use something like Vagrant

#!/bin/bash
# TODO: make this dynamic, download image if not exists
IMGDIR=$HOME/Devel/images
BASE_IMG=focal-server-cloudimg-amd64.img
NAME=$(basename $PWD)
VMDIR=.vm
SSH_RSA=$(cat ~/.ssh/id_rsa.pub)
if [[ -d $VMDIR ]]; then
echo "VM already exists, to re-create, run vm-destroy.sh first"
exit 1
fi
mkdir -p $VMDIR
# Generate meta-data and user-data files
cat << EOF > $VMDIR/meta-data
instance-id: $NAME
local-hostname: $NAME
EOF
cat << EOF > $VMDIR/user-data
#cloud-config
users:
- name: ubuntu
ssh_authorized_keys:
- $SSH_RSA
sudo: ['ALL=(ALL) NOPASSWD:ALL']
groups: sudo
shell: /bin/bash
EOF
# Generate file system from base image
qemu-img create -b $IMGDIR/focal-server-cloudimg-amd64.img -f qcow2 -F qcow2 $VMDIR/$NAME.qcow2 10G
# Generate ISO image for cloudinit
genisoimage -output $VMDIR/cidata.iso -V cidata -r -J $VMDIR/user-data $VMDIR/meta-data
# Virt-install
virt-install \
--name $NAME \
--ram 1024 \
--vcpus 1 \
--import \
--disk path=$VMDIR/$NAME.qcow2,format=qcow2 \
--disk path=$VMDIR/cidata.iso,device=cdrom \
--os-variant=ubuntu20.04 \
--memorybacking access.mode=shared \
--filesystem source=$PWD,target=code,accessmode=passthrough,driver.type=virtiofs \
--noautoconsole
#!/bin/bash
NAME=$(basename $PWD)
VMDIR=.vm
if [[ ! -d $VMDIR ]]; then
echo "VM does not exist, use vm-create.sh to create it."
exit 1
fi
virsh destroy $NAME
virsh undefine $NAME
# some files inside the .vm dir will be owned by qemu, don't have a better idea right now
# maybe try to run the whole thing in qemu://session instead?
sudo rm -rf $VMDIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment