---
title: DIY CLI CI
lang: en-GB
author: Maggie Harley
---

CI services like [Travis CI](https://travis-ci.org) and
[CircleCI](www.circleci.com) provide systems for testing your project on many
different platforms. But they're kinda developed for large or decentralised
projects, and in reality they don't support _that_ many systems, especially
more out-there variants of computer (e.g.  big-endian CPUs). On top of that,
you don't have an awful lot of control over what gets run on the CI system -
Travis CI, for example, [cannot cache prerequisites without the use of a
third-party.](https://github.com/travis-ci/travis-ci/issues/7590) To top it
off, they're _slow_: you often have to re-run code in identical scenarios, and
that's no fun.

Instead, why not make a simple internal system that runs virtual machines -
images you specify, with any configuration you want. All without requiring a
GUI, and all without using `sudo` on your host system!

The aim here is to create a system that starts up a VM, `ssh`es into it, runs a
script passed to it through `stdin`, and returns the output to terminal,
discarding the VM.

# I'm Using [QEMU](https://www.qemu.org/)

Any VM toolset _should_ be able to do what I do with QEMU, but there might be
some instructions here that are QEMU-specific.

To use QEMU without a graphical interface, pass it `-nographic`.

# Things Worth Knowing Before Trying to Know This

- QEMU stuff (if you're using QEMU)
  - [basic usage](https://wiki.archlinux.org/index.php/QEMU)
  - [image manipulation](https://en.wikibooks.org/wiki/QEMU/Images)
  - [snapshots](https://wiki.qemu.org/index.php/Documentation/CreateSnapshot)
  - [save states](https://superuser.com/questions/937061/save-qemu-vm-state-like-in-virtualbox)
  - [the monitor](https://en.wikibooks.org/wiki/QEMU/Monitor) (just the fact
    that it exists really)
- Bash's [IO redirection abilities](https://www.tldp.org/LDP/abs/html/io-redirection.html)
- [SSH keys](https://wiki.archlinux.org/index.php/SSH_keys)

# Configuring Your VM

![Configuring computers inside computers.](./assets/pc-in-pc.png)

## Add a User that isn't Root

Most systems don't like the `root` user logging in over SSH, and since we plan
on doing just that, you'll have to make a new user.

When making a password for this user, make sure it's not an empty
password, since SSH doesn't seem to play well with that either.

### Give a User (Passwordless) `sudo` Privileges (if You Need To)

Some systems ask for a password when attempting to use `sudo`, and that would
prevent running scripts that require `sudo` without user intervention.

Enabling passwordless `sudo` on your VM should be quite simple: run `visudo` and
add the following lines at the bottom of the opened file:

```bash
%wheel ALL=(ALL) ALL
Defaults:%wheel !authenticate
```

It's possible the file already has these lines, but commented out, in which case
it's probably better to uncomment those lines instead of adding new versions.

Now you should be able to run `sudo` as your user on your VM without requiring a
password.

## Add Your Server to the VM's Known Hosts

When you `ssh` into a computer, it will usually ask for the password of the user
you're trying to log in as, which would break automation again (or require you
to include the password in a bash script or similar - don't do that). Installing
your private key on the VM allows the VM to check that the connection is coming
from a legitimate source without the need of a password.

Copy the contents of your `~/.ssh/id_rsa.pub` file to the end of the VM's
`~/.ssh/authorized_keys` file - the easiest way is probably using copy and
paste across two terminals - trying to do it through `ssh` or similar is just
wonky. If your VM doesn't have a `~/.ssh/authorized_keys` file, create it. It's
important that you do this for the user you made on the VM, and **not** the
`root` user, and also that only the user has permissions to read their
`~/.ssh`:

```bash
chmod 700 ~/.ssh
```

## Snapshots and Save States in QEMU

Snapshots in QEMU are great - they let you base an image off another image as a
sort of template, so that you can run a system and have it edit files without
editing the template image. Even better, passing the `-snapshot` flag to QEMU
causes it to create a temporary snapshot file for that run only, which is
removed when QEMU terminates.

Equally as nifty is QEMU's ability to save and load a VM's state, using
`savevm` and `loadvm` from the monitor. This option also has a command-line
flag: `-loadvm`. This lets you skip a VM's rather lengthy startup times, which
is a huge time-saver for small test suites. Just use `savevm` from the monitor
at a time that your VM is fully booted and ready to run things, and make sure
to give it a catchy name.

Unfortunately, attempting to use both of these flags on the same command-line
invocation will cause QEMU to try and load a save state from its newly-created
temporary snapshot, which will fail. Instead, it's necessary to use a
non-temporary snapshot file - but even then, running a VM on this snapshot would
edit the snapshot for future uses, which is also not what we want. The solution
is to emulate the `-snapshot` flag yourself: upon request, create a snapshot
(either by generating it from the original image or copying a ready-made
snapshot file), run the VM using it, then delete the used snapshot after you're
done with the VM instance.

# Setting Up Your VM's Host

## `ssh` Into Your VM

Finally, with the right `qemu` line, you should be able to start up your VM and
be able to `ssh` into it. At this point, your command for initialising the VM is
probably big enough to put in its own script file. The following script should
start up the VM with a temporary snapshot, and with a port forwarded to its
host to allow the `ssh` connection:

```bash
#!/bin/sh

temp_snapshot=$(mktemp XXXXXXXX.qcow2) 
cp your_template_snapshot.qcow2 $temp_snapshot
trap "rm -f $temp_snapshot" EXIT

qemu-system-x86_64 \
    -m 512 \
    -hda $temp_snapshot \
    -net user,hostfwd=tcp::your_port-:22 \
    -net nic \
    -enable-kvm \
    -nographic \
    -loadvm your_save_state_name
```

It might look like the command's hanging, but really it's that the VM has been
loaded at a point in time that it's already printed its PS1 and is awaiting user
input. Just hit enter or something and all should be good.

Now from another terminal, connect to your VM and run a script from your host
remotely:

```bash
ssh your_vm_user@localhost -p your_port "sh -s" < your_script.sh
```

You should see the output of this script in this second terminal. If so,
perfect! You did it.

## Automating the Above

Really you want all of this done in the same terminal, and with only writing one
command. Easy:

```bash
#!/bin/bash

PORT=your_port

output_file=$1

temp_snapshot=$(mktemp XXXXXXXX.qcow2) 
cp your_template_snapshot.qcow2 $temp_snapshot

qemu-system-x86_64 \
    -m 512 \
    -hda $temp_snapshot \
    -net user,hostfwd=tcp::${PORT}-:22 \
    -net nic \
    -enable-kvm \
    -nographic \
    -loadvm your_save_state_name &> /dev/null &
qemu_pid = $!

trap "kill -TERM $qemu_pid && rm -f $temp_snapshot" EXIT

sleep 1 # this can probably be smaller

ssh your_vm_user@localhost -p $PORT "sh -s" | tee $output_file
```

Now you have a bash script that starts up a VM, `ssh`es into it, runs a script
passed through `stdin`, and sends you the output. It can also optionally save
the output to a file.  Because it uses `mktemp`, it can also have several
instances running in parallel.

# Where Next

## Remote Remote Control

The next step would be to make a script to run these jobs not just from the VM's
host, but from _any_ computer that could connect to it. There's plenty of
options for this, with a simple HTTP server probably making for the most robust
and cross-platform solution. It's easy enough to do with more `ssh`ing though:

```bash
ssh your_user@your_server "the_above_script.sh" < your_test_script.sh
```

## Git~~Hub~~ Integration

Rather than having your tests fail _after_ pushing them to the team repo (and
feeling like a right dork), why not have them fail _before_ pushing them?
[Git hooks are your
friends](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks).

## Auto-Deployment/Other Things on Success/Failure

Big CI systems like their multiple stages with different workflows and step-by
step one-script-at-a-time sequences, and I suppose it would be quite a lot of
effort to do a similar thing here. But why not just include your deployment
logic at the end of the test script you pass to the VM?

I suppose any hefty post-test stuff will run slowly if it's being run on a
virtual machine, but it also shouldn't be too difficult to edit the VM-host's
script to handle the test script, a pass script, and a failure script.

## Dependency Caching

You don't want to have to download your dependencies every time you run tests:
just create your snapshot _after_ installing them!

For testing things like different compiler versions, you could have a different
snapshot for each setup, or you could just have all the different versions
installed in one image.

# That Should be It

Hopefully you can follow my thinking here and create your own internal CI
system. If you've got any questions, or think something in this post needs
fixing, please let me know!
