Linux – How to execute commands as root in git post-receive hook

bashgitlinuxsudoupstart

I just recently set up a remote git repo on a server for a web app running as an Upstart service. I'd like to use the post-receive hook to trigger actions that are required to update the application code and stop then restart the upstart service. This is my repo.git/hooks/post-receive file:

#!/bin/bash
export GIT_WORK_TREE=/var/www/current/myapp/
echo "Checking out new files and restarting app"
echo $USER
git checkout -f
sudo /sbin/stop myapp-service
sudo /sbin/start myapp-service

Based on the info I read here: askUbuntu.com, the way to get the upstart commands to execute as root is to edit my visudo file. Here is the relevant snippet:

%sudo   ALL=(ALL:ALL) ALL
admin   ALL=(ALL:ALL) NOPASSWD: /sbin/start myapp-service /sbin/stop myapp-service

But when I git push to the remote, I get output like:

$ git commit -am "test" && git push prod master
[master 59ffccd] test
 1 file changed, 1 insertion(+), 1 deletion(-)
Counting objects: 11, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 544 bytes, done.
Total 6 (delta 4), reused 0 (delta 0)
remote: Checking out new files on production and restarting app
remote: admin
remote: 
remote: sudo: no tty present and no askpass program specified
remote: Sorry, try again.

I've checked that the correct user is executing the post-receive script (admin, as echoed above).

Can someone help me stop and then start the Upstart job in a git post-receive hook script? Python, PHP, or node.js javascript scripts would also be acceptable if they would be able to exec the upstart command more easily than bash (I'm a bash newbie)

I looked in my auth log and this is what I have:

Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): auth could not identify password for [admin]
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): conversation failed
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): auth could not identify password for [admin]
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): conversation failed
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): auth could not identify password for [admin]
Apr 24 19:35:21 myhost01 sudo:    admin : 3 incorrect password attempts ; TTY=unknown ; PWD=/home/admin/myapp.git ; USER=root ; COMMAND=/s$
Apr 24 19:35:21 myhost01 sudo: unable to execute /usr/sbin/sendmail: No such file or directory
Apr 24 19:35:21  myhost01 sudo: pam_unix(sudo:auth): conversation failed

Best Answer

You need to separate the commands in your sudoers file using commas. Right now, you're authorizing a single command: /sbin/start myapp-service /sbin/stop myapp-service.

You need to write admin ALL=(ALL:ALL) NOPASSWD: /sbin/start myapp-service, /sbin/stop myapp-service.

Related Question