Systemd services to control VMs

Systemd services can provide an easy way to manage the on/off state of the VMs (systemctl start/stop), and can (optionally) start VMs automatically when the host system boots.

Warning

libvirt has its own autostart feature, but we’re not using that, because I couldn’t get it to work in user session mode. Systemd units per VM feels nicer anyway.

Download libvirt python interface

Tip

You should now be in your normal workstation account Bash shell.

[bash]: Run this on your workstation:
(set -e
sudo mkdir -p /usr/local/src/
sudo su -c "cd /usr/local/src && git clone https://github.com/EnigmaCurry/virsh-start-stop"
)
CREDITS

EnigmaCurry/virsh-start-stop is my own fork of avollmerhaus/virsh-start-stop which has been slightly customized for this configuration. Thank you to avollmerhaus for creating this service manager!

Create Unit template

This is an instantiable template used for all VM services:

[bash]: Run this on your workstation:
VM_ADMIN=${VM_ADMIN:-libvirt-admin}
cat << EOF | sudo tee /etc/systemd/system/libvirt@.service
[Unit]
Description=${VM_ADMIN} VM: %i
Requires=libvirtd.service
After=libvirtd.service

[Service]
Type=oneshot
RemainAfterExit=true
User=${VM_ADMIN}
Group=libvirt
Environment="XDG_RUNTIME_DIR=/run/user/$(id -u ${VM_ADMIN})"
ExecStart=/usr/bin/python /usr/local/src/virsh-start-stop/src/virsh_start_stop/virsh_start_stop.py --machine %i --state started
ExecStop=/usr/bin/python /usr/local/src/virsh-start-stop/src/virsh_start_stop/virsh_start_stop.py --machine %i --state stopped

[Install]
WantedBy=default.target
EOF

Enable each VM service

This will instantiate the VM service template, and enable a VM named debian-dev, which will automatically start on workstation boot:

[bash]: Run this on your workstation:
NAME=${NAME:-debian-dev}
sudo systemctl enable --now libvirt@${NAME}
sudo systemctl status libvirt@${NAME}