Skip to content

Instantly share code, notes, and snippets.

@brccabral
Created May 8, 2024 03:44
Show Gist options
  • Save brccabral/1c489dfd01546a78937d6ecfe9bfdeb8 to your computer and use it in GitHub Desktop.
Save brccabral/1c489dfd01546a78937d6ecfe9bfdeb8 to your computer and use it in GitHub Desktop.
Git Tips

Git Tips

Hook: post-receive

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 -f

But 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-receive

Then, create this new file /etc/sudoers.d/nopass-my-post-receive with this content:

userName ALL=(ALL) NOPASSWD: /home/userName/.local/bin/my-post-receive

This 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.

#!/bin/bash
git --work-tree=/var/www/MyApp --git-dir=/home/userName/MyApp checkout -f
userName ALL=(ALL) NOPASSWD: /home/userName/.local/bin/my-post-receive
#!/bin/bash
sudo /home/userName/.local/bin/my-post-receive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment