Sudo - How to allow a user to manage a service ?

Bash Liste Des Attaques Ovh

About

How to allow a user to manage a service with sudo

Steps

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).

Create a sudoer file

In the below file:

  • the service is called service_name
  • the user is called user_name

just replace the value with yours.

The file /etc/sudoers.d/service_name contains two entries

  • a command alias that list all command permittede
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
  • and the user specification
user_name ALL = (ALL) NOPASSWD: BACKEND_SERVICES

This user specification means:

  • the user user_name
  • on all machine ALL
  • may run as everybody (ALL) (the command may then be run also as root)
  • without specifying a password NOPASSWD: (this is called a tag)
  • the command specified by the alias BACKEND_SERVICES

Copy it

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

Test it

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.







Share this page:
Follow us:
Task Runner