Post-Image

Use Github Webhooks to automatically push your changes to a webserver.

Posted on

I’ve installed a little Github Webhook for my portfolio repository so whenever I make changes to the repository they automatically get deployed to my webserver.

For this little trick to work you have to have a git client installed on your webserver. Also the shell_exec php function has to be active so we can run the git pull command from php.

First we have to clone the repository on your server in the directory where the website should be.

 git clone https://github.com/nahakiole/robinglauser.ch .

Then we have to create two files, one php file as the webhook and a shell script which resets the repository and pulls the latest changes.

push (Shell script)

 git reset --hard HEAD
git pull
git submodule update --init --recursive

githook.php (Githook :D)

 <?php

shell_exec( 'chmod +x push' );
shell_exec( './push' );
echo 'It works!';

After you’ve created the two files you can test them by calling the githook.php file from your webserver, this should then reset the repository and pull in the latest changes.

If this works until here we can add the githook in our repository under “Settings”, “Webhooks and Services” and then “Add webhook”

In the field “Payload URL” you can then add the url to your githook.php file. I’d recommend to change the “Content type” to “application/x-www-form-urlencoded”.

The rest of the options can be left to the defaults.

Now if you push changes to the repository or even make changes directly over the webinterface they will get updated on your webserver automatically without the use of any other service.

This is of course only usable for small static websites, although it could be extended to run more commands in the push shellscript.

If you have any questions or if you’ve run into any issues while following this tutorial, please leave a comment and I will get back to you.

Leave a Reply