Hacker News new | ask | show | jobs
by qbasic_forever 1045 days ago
You might like systemd's run command, it's a hidden little gem that basically does what your tool does--it turns some CLI params into a transient service file: https://www.freedesktop.org/software/systemd/man/systemd-run...

I dunno if this was a more recent addition to systemd, but it's pretty slick in my limited use. I use it for exactly the scenarios you mention, like quickly spinning up some local user services during development. It can do stuff like setup a listening socket, timer (cron) or file watcher service all from the CLI too.

3 comments

Great tip. I would also couple it with the —-user flag so the service runs as your user. Stuff like this shouldn’t have root permissions anyway.
That's a good thought. `sudo` is needed for writing to `/usr/`. The service being set up does not have root access. The value of `User=` is $SUDO_USER (hp- my regular non privileged user who initiatiated sudo) instead of $USER (root).

https://github.com/servicer-labs/servicer/blob/762801e3c07b1...

Typically the `User=` directive is used to specify what the user the service runs in.

There is still a benefit to requiring root to create the service file though: If the service is compromised when it's running as `User=`, it can't modify the systemd service file itself, which is owned by root.

That's interesting! I wasn't aware of this command when I started working on servicer. Anyway, there are a couple of utilities like `ser status` and `ser which` which you might find useful.
TIL, Pretty cool!

But I suppose there isn't away to run these transient services as boot because they are definition gone after they have stopped?

It's actually very easy!

You can abuse the fact that systemctl has the edit subcommand. It meant to modify the existing service file, but nothing means you can't just save it out elsewhere and then modify it.

Additionally, if it's a long running service it should be located where other systemd unit files are located (`$HOME/.config/systemd/user/` for user units, `/etc/systemd/system/` for service units) and just copy them while the unit is still running.

  systemd-run --user -u test -t bash
  cp $HOME/systemd/user/test.service /new/path/for/test.service
Of course this requires it to live long enough.
Theoretically one-shot service that launches a shell script with systemd run on boot could do the trick. OTOH it's probably easier to just write a tiny service at that point.

Generally results of -run services can be captured through journalctl, so it's possible to run systemctl show on them and get the config.