Skip to content
Logo Theodo

Stop Wasting your Time Restarting Services Manually After Deployment: Visudo It!

Paul Jehanno2 min read

© xkcd

Here is how I managed to save time on my PHP project by enabling restarting services automatically during deployment.

Basic capistrano configuration

When I work on PHP projects I deploy using Capistrano, a tool that enables scripting of deployment tasks. During my previous project, I had to manually log in to my server and restart the php-fpm service after each deployment. I wasted almost one hour of my time every week running sudo service php5-fpm restart 10 times a day. Moreover, every once in a while I forgot to restart the service and I had to spend 30 minutes more to find out why I couldn’t see my new feature on my website.

To save time, I wanted capistrano to do it for me:

task :restart_php do
  on roles(:app) do
    execute "sudo service php5-fpm restart"
  end
end

To do so, I needed superuser permissions. I considered giving sudo rights to the application user, but this would represent a major security issue: say there is a security breach on your application that enables an attacker to take control over the application user, they could take control over the whole server.

A solution is to grant superuser permission on a specific command.

Introducing the /etc/sudoers file and visudo command

Log in to your server as root and run sudo visudo. Visudo enables you to edit the /etc/sudoers file, in which your computer grants superuser permissions.

I added the following line:

www-data ALL=(root) NOPASSWD: /usr/sbin/service php5-fpm restart

The line is divided into 4 parts:

You can now understand why this line in the file is the source of root superpowers:

root ALL=(ALL) ALL

With great power comes great responsibilities

Before you enable all users to run sudo commands without being asked any password (which is possible but strongly advised against), take caution using visudo: granting superuser commands must be used with parcimony.
Finally, you may ask yourself why I used visudo instead of vim /etc/sudoers file. Never edit directly the /etc/sudoers file. Visudo includes checks before saving the edited file: it prevents it from syntax errors that would cause major superuser problems on your computer.

Liked this article?