Virtualbox VM autostart on headless server
Systemd, kernel modules and services
linux
vm
Intro
If you want to run virtualbox on a headless server and need your vms to start with the system, this is for you.
- Installing the official virtualbox package gets you out of the box capabilties to autostart vms (after a bit of config). In turn, you will run into a brick wall named secure boot, self-signing kernel modules with a machine owners key (MOK) and automating that yourself.
- Using the virtualbox version from the ubuntu repo deals with that by providing and configuring dkms (dynamic kernel module support).
- In turn, this lacks the systemd services to autostart the vms. Below I show how to set it up.
Implementation
First we need a systemd unit file that starts our vm via the vboxmanage
CLI command. Thankfully, someone did that in the virualbox forums. Depending on how you set up your system the user and group settings will need adjustment.
# /etc/systemd/system/vbox@.service
[Unit]
Description= Guest VM %I
After=systemd-modules-load.service network.target virtualbox.service
Requires=systemd-modules-load.service virtualbox.service
Before=runlevel2.target shutdown.target
[Service]
User=red
Group=vboxusers
Type=forking
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
ExecStart=/usr/bin/VBoxManage startvm %i --type headless
ExecStop=/usr/bin/VBoxManage controlvm %i acpipowerbutton
[Install]
WantedBy=multi-user.target
- Due to the
@
1 in the file name the unit file is a template and can be used to create start-services for several vms.
sudo systemctl enable autostart_vm@<vm-name>
# verify config (vm must not be running!)
sudo systemctl daemon-reload
# check if the service can start
sudo systemctl start autostart_vm@<vm-name>
# check status
sudo systemctl status autostart_vm@<vm-name>
# if all is well enable it to start on boot
sudo systemctl enable autostart_vm@<vm-name>
Ensuring kernel modules are loaded
- It is essential to ensure that the necessary kernel modules for virtualbox are loaded at boot by naming them in a file in
/etc/modules-load.d/
. Otherwise the entire virtualbox hypervisor and our vm wont start. - Beware that the name of the kernel modules may differ depending on your distro and version.
- I found them by
lsmod | grep vbox
Coda
- I went with virtualbox because I know it, it works well with vagrant which I use to quickly spin up vms for testing.
- In the future I will use the solution baked right into the linux kernel:
kvm
(actually qemu+kvm+libvirt). At the time i just needed a way to run vms at boot and move on setting up the new machine.