Webhooks allow you to build or set up integrations which subscribe to certain actions on GitHub.com. When one of those events is triggered, Github sends a HTTP POST payload to the webhook's configured URL. Webhooks can be used to update an external issue tracker, trigger CI builds, update a backup mirror, or even deploy to your production server. You're only limited by your imagination. If you would like to configure URL or events, you are supposed to run this url the following.
https://github.com/[owner]/[repository]/settings/hooks.
You'll see this page on that and click the Add webhook button to configure our new webhook.
After the typing your password, from now on you are able to configure first webhook. It's truly so straightforward.
At this point, we're supposed to type a payload url. It should be the file which welcomes the payload from Github. And secret sections helps to authorization. After a webhook creation, Github sends a request with this secret. If the secret is same with our response from that file, Github figures out that. To allow that, I've created a PHP file github_webhook.php
like this.
<?php
echo 'thisismertblogsecret';
If everything is smooth, you will have been seen Webhook list on your Github setting page. From now on, all push events will have been sent your payload url. To handle the request, I've changed the file.
#echo 'thisismertblogsecret';
if ($_POST && $_POST['payload']){
$payload = json_decode($_POST['payload'], true);
if (isset($payload['ref']) && $payload['ref'] == 'refs/heads/master'){
exec("/usr/bin/git pull origin master >> ./webhook.log 2>&1 && echo $(date) >> ./webhook.log");
}
}
Well, we've simple a file. It handles the requests from Github events. If the request to push, it runs the pull command. And it sends the output a file webhook.log
named. Let's make a test.I am going to send push command and it will be running pull command.
As you see, the output was typed into our log file. In addition, pull process was succeed.
Common Errors
1-) error: cannot open .git/FETCH_HEAD: Permission denied
Just run this commands the following.
chown root:nginx .git/FETCH_HEAD
chmod 775 .git/FETCH_HEAD
2-) Permission denied (publickey). fatal: Could not read from remote repository.
This is easy as well. Imagine that, github_webhook.php is run by Nginx user. Not root user. So, every user has a key in Ssh connections. You are supposed to create a key for Nginx user.
sudo -u nginx ssh-keygen -t rsa
You could see the keys with this path, /var/lib/nginx/.ssh/
.
Right, then you have to add this key into deploy keys of the repository, https://github.com/[owner]/[repository]/settings/keys. From now on, you will able to get rid of that.
Well, my talking is over about that. In some cases, Github Webhook is truly helpful for developers. If you have any questions or trouble don't hesitate to type.
Top comments (0)