How to execute commands as root in git post-receive hook
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
.
Ok,I figured it out. I had to create a separate script containing only the commands I wanted to run as root.
#!/bin/bash
sudo /sbin/stop myapp-service
sudo /sbin/start myapp-service
Then, in my post-receive script do:
#!/bin/bash
export GIT_WORK_TREE=/var/www/current/myapp/
set -x
echo "Checking out new files on production and restarting app"
echo $USER
git checkout -f
sudo /home/admin/restart-myapp
And finally in my visudo:
%sudo ALL=(ALL:ALL) ALL
admin ALL=(ALL) NOPASSWD: /home/admin/restart-myapp
Hope this helps someone else
I have a file in /etc/sudoers.d/root_group
that just has the line %root ALL=(ALL) NOPASSWD: ALL
, and I add accounts to the group root to allow them to use sudo
without a password.
I'm sure there are security implications for file permissions that didn't consider user accounts being in the group "root", but if you're concerned, a different group can be used. Just change the line to %my_new_group ALL=(ALL) NOPASSWD: ALL
and add the relevant accounts to my_new_group.