Systemd Run - Systemd Transient Units

spawn and kill systemd units without configurations

Introduction

systemd is a controversial topic amongst Linux enthusiast, some like it, some hate it. I understand why people dislike systemd but for me personally, systemd has served me well, I still use systemd (arch BTW). Benno Rice has an excellent talk on The Tragedy of systemd that summarizes my attitude towards systemd.

It is a complex piece of software and I still learn new things about systemd every now and then. One such thing I learned recently was systemd-run.

systemd-run offers an excellent way to spawn transient systemd units. You can use a single command to spawn up a systemd unit and interact with it just like how you would with a normal systemd unit

This can be useful if elements of the process managed by a systemd unit varies with each run.

The requirement that led me to the discovery of systemd-run is managing multiple VPN connections. I have a bunch of OpenVPN configuration files stored on the filesystem. I do not want to write systemd service unit files for each and every OpenVPN configuration. This is the script that I came up with that utilizes systemd-run & fzf to solve this problem.

VPN_CONFIG_FILE=$(ls *.ovpn | fzf)

sudo systemd-run \
   --unit=vpn-connection \                      # name of the transient systemd unit
   --property=WorkingDirectory=$(pwd) \         # additional properties to be set on the systemd unit
   /usr/bin/openvpn --config $VPN_CONFIG_FILE   # ExecStart 

since running OpenVPN requires root permissions, I am creating a systemd unit using sudo. you could even use systemd-run using the --user flag to run processes that do not require root. For running the python HTTP server to serve the contents of a directory, I could use this command.

systemd-run --user --unit=fileserver /usr/bin/python -m http.server 

if a systemd-run unit fails, you just need to run systemctl reset-failed to reset the service and reinitialize this service.