Configure a systemd Service to Perform Side Effects and Corresponding Cleanup
Problem and Motivation
For a Linux-based demo setup, I need certain side effects and corresponding cleanup steps every time the system boots or relevant system configuration changes. I’m using NixOS, and systemd is the easiest and most powerful way to manage setup tasks at system startup or on substantial system configuration changes in NixOS. I didn’t need a daemon running in the background (which is the major purpose for systemd services), but specifically certain side effects and corresponding cleanup. Lightweight shell script to perform the relevant actions are more than sufficient – invoked by systemd.
⚠️ Please note that using systemd is one possible way of achieving this. There might be others, depending on your system / Linux distribution.
Solution
From my understanding, research, and reading the man pages, using a Type=oneshot
service with RemainAfterExit=true
is the right configuration to achieve that. The following (with manually removed clutter) configuration file my-service.service
shows a valid complete example:
[Unit] After=libvirtd.service Description=setup-libvirt-vm-win10-vm [Service] ExecReload=/path/to/your/setup-script --reload ExecStart=/path/to/your/setup-script --start ExecStop=/path/to/your/setup-script --stop RemainAfterExit=true Type=oneshot [Install] WantedBy=multi-user.target
We need Type=oneshot
so that systemd blockingly waits for the command behind ExecStart
to exit. We need RemainAfterExit=true
so that ExecStop
is not immediately executed after ExecStart
finishes, but when the service is (naturally or manually) stopped, as if it was a daemon.
Note that After=<service>
and WantedBy=<target>
highly depend on your use-case. This is what worked in my case.
0 Comments