brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a systemd template unit runs the same service for several names

Systemd
~/tips/tip-systemd-template-units

[Unit]

Write one unit file with %i and start as many named instances of it as you need.

When you need the same job for several targets, I wouldn’t copy the unit file. A template does it with one file and an instance name.

A template has an @ right before the suffix, and %i stands for whatever comes after the @ when you start it:

# /etc/systemd/system/[email protected]
[Unit]
Description=Backup of %i

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh /srv/%i

Then start instances by name:

sudo systemctl start [email protected] [email protected]
systemctl list-units 'backup@*' --all

Each instance is a separate unit with its own status, logs and failures. A quick test with ExecStart=/bin/echo hello %i from %n started as [email protected] logged hello world from [email protected], so you also see what %n gives: the full unit name.

To enable an instance at boot, enable it by its full name, like systemctl enable [email protected], with a WantedBy= in an [Install] section. Timers can be templates too, so [email protected] pairs with [email protected].

Instance names are plain strings. Slashes and spaces need escaping; systemd-escape [email protected] "/srv/my data" prints the right name.

Further reading: systemd.unit man page, systemd-escape man page

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass – dbpass.cred systemd-analyze timespan 1h30min All Systemd tips (88) All topics

Link