How to use sudo in a systemd service script?

You don’t. sudo is for interactive use. Doing anything else with it is either incredibly cumbersome or rips security holes into your system. NixOS makes this rather hard anyway due to how setuid is handled.

Assign the user to your service that needs to do the actual business logic - in this case, that looks like postgres. If you need to execute part of it on files not owned by this user, assign proper groups so all users who need access have it, or where you need elevated privileges use the + prefix (note you need to use serviceConfig.ExecStartPre and co. to use that, since the NixOS module turns all this into a bash script which is called instead).

Sometimes your task may also be more nicely represented by a set of inter-dependent services, which can then have more specific permissions set, based on what they actually do. You’d for example use systemd.tmpfiles to ensure a directory exists.

4 Likes