How to allow a user to manage a service with sudo
sudo is a program that defines rules over what a user may run as command.
It allows to add sudoer file (configruation file) into the directory /etc/sudoers.d that defines the user specification (ie what a user may do).
In the below file:
just replace the value with yours.
The file /etc/sudoers.d/service_name contains two entries
Cmnd_Alias SERVICE_NAME_SERVICES = /usr/bin/systemctl start service_name, /usr/bin/systemctl stop service_name, /usr/bin/systemctl reload service_name, /usr/bin/systemctl restart backend, /usr/bin/systemctl status service_name, /usr/bin/systemctl enable service_name
user_name ALL = (ALL) NOPASSWD: BACKEND_SERVICES
This user specification means:
Just copy the file to /etc/sudoers.d/
The file is automatically included. You can set the inclusion in the last line of the file /etc/sudoers
## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
For instance in Ansible.
- name: Copy the sudoer file
template:
src: 'myapp.sudoer'
dest: '/etc/sudoers.d/myapp'
mode: 0750
Login as user_name and run the following command
sudo systemctl restart service_name
The user should be able to execute it without any password.