I have a repo on my machine, MyApp, I have a Bare Git Repo on a remote server production at /home/userName/MyApp.
When pushing to remote production, I need to update the code in the actual location /var/www/MyApp, but it needs root/sudo permission.
In the bare repo, add file /home/userName/MyApp/hooks/post-receive. This file is always executed after a push.
The idea is to execute this:
#!/bin/bash
git --work-tree=/var/www/MyApp --git-dir=/home/userName/MyApp checkout -fBut because work-tree is protected, this need to run as sudo, but the push can't input password.
So, create a separated script at /home/userName/.local/bin/my-post-receive with the git command above.
In the hook, use this:
#!/bin/bash
sudo /home/userName/.local/bin/my-post-receiveThen, create this new file /etc/sudoers.d/nopass-my-post-receive with this content:
userName ALL=(ALL) NOPASSWD: /home/userName/.local/bin/my-post-receiveThis tells visudo to ignore password for user userName to execute my-post-receive.
Now, in my work machine doing git push production master will execute the hook and update the protected folder without sudo password.