Sudoers nopasswd switch user and run node not working

githooknode.jssusudo

I'm trying to prevent a password prompt on a command that runs node as the www user by adding the following line to the bottom of my /etc/sudoers file:

gituser ALL=(ALL) NOPASSWD: /usr/bin/sudo -u web-user NODE_ENV=production /path/to/node app.js

I also tried putting the command in a shell script and running that but no joy either:

gituser ALL=(root) NOPASSWD: /usr/local/sbin/startnode

Does anyone have any ideas on what I'm doing wrong?

Ultimately I'll be running this as an upstart service so the command will be "sudo service runnode stop/start" and triggered from a git hook but I guess the principle will be the same.

FYI, full contents of sudoers file:

Defaults        env_reset
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Defaults
root    ALL=(ALL:ALL) ALL
%admin ALL=(ALL) ALL
%sudo ALL=(ALL) ALL

gituser ALL=(ALL) NOPASSWD: /usr/bin/sudo -u web-user NODE_ENV=production /path/to/node app.js
gituser ALL=(root) NOPASSWD: /usr/local/sbin/startnode

Best Answer

Thanks everyone for your answers. I managed to get it working in the end with the help of this post by doing the following:

1. Using Separate Script

Add this line to sudoers file (using visudo).

gituser ALL=(web-user) NOPASSWD: /usr/local/sbin/startnode

Contents of file /usr/local/sbin/startnode changed to following:

#!/bin/bash

cd /var/www/api.vitdsunshine.com/sun-express

########## BEFORE
# sudo -u web-user NODE_ENV=production /path/to/node app.js

########## AFTER
NODE_ENV=production /path/to/node app.js

This will now work:

$ sudo -u web-user startnode

2. Using the full command

Add this line to sudoers file (using visudo).

gituser ALL=(web-user) NOPASSWD: /path/to/node

Trying to set an env variable as part of the command causes it to fail.

$ sudo -u web-user NODE_ENV=production /path/to/node app.js
sudo: sorry, you are not allowed to set the following environment variables: NODE_ENV

The solution: you have to set this env var in web-user's .bashrc file or /etc/environment.

$ sudo -u web-user /path/to/node app.js
env production
Express server listening on port 9000