Systemd – Grant User Sudo Powers to Manage Systemd Service Without Password

sudosystemd

I have one non-root user, and I would like to give them sudo permission to start & stop (etc.) a systemd service file without needing a password.

I tried to just make the following file in /etc/sudoers.d/servicename (where [username] and [servicename] are the actual names):

[username] ALL=(root) NOPASSWORD: systemctl start [servicename]
[username] ALL=(root) NOPASSWORD: systemctl stop [servicename]
[username] ALL=(root) NOPASSWORD: systemctl restart [servicename]

(repeated for lots of system commands, like reload/try-restart/enable/…)

But visudo told me that was a syntax error. How can I fix that?

I want to put in scripts (which are being run as this non-root user) sudo systemctl stop [servicename].

Ubuntu Linux 18.04, systemd from ubuntu (which for this is v245). I also want this to work on Ubuntu 20.04.

Best Answer

You can implement what you want by using the following:

Cmnd_Alias USER_SERVICES = /usr/bin/systemctl start [servicename], /usr/bin/systemctl stop [servicename], /usr/bin/systemctl restart [servicename]

[username] ALL=(ALL) NOPASSWD:USER_SERVICES

You can add more commands to USER_SERVICES by placing a comma (,) between them. Always use the full path for the command.

Related Topic