Web Hooks for Gitlab using PHP and Shell Scripts

The process involves:

1. PHP script to run on URL call

2. The PHP script calls a bash script which does actual work.

$access_token = ‘same-token-mentioned-in-webhook-url’;

$access_ip = array(‘xx.xx.xx.xx’); //ip address of the gitlab server

$client_token = $_GET[‘token’];

$client_ip = $_SERVER[‘REMOTE_ADDR’];

$fs = fopen(‘./webhook.log’, ‘a’); //creates a log in the same directory as your php script

if ($client_token !== $access_token)
{
echo “error 403”;
fwrite($fs, “Invalid token [{$client_token}]”.PHP_EOL);
exit(0);
}

if ( ! in_array($client_ip, $access_ip))
{
echo “error 503”;
fwrite($fs, “Invalid ip [{$client_ip}]”.PHP_EOL);
exit(0);
}

exec(“sudo location/of/bash/script”);

?>

#!/bin/bash

cd /location/to/store/git/files
git checkout
git reset — hard HEAD
git clean -f -d
git pull origin >> /choose/a/locaion/for/log
echo “” >> /same/log/locationWe have called Bash script with sudo permissions in PHP. so, when we run the script remotely, it will wait for the password. In order to avoid that we need to give user, a permission to execute a sudo command without prompt of the password. For that, we need to edit sudoer’s file

Note:

The location where git repository is downloading is properly git configured and you use ssh key with empty pass phrase to download git repository

sudo visudo //to access the sudoer’s file in safemode

user ALL=(ALL) NOPASSWD:/path/to/script.sh

1. Check permissions of script(i.e. Does user belong to group that can execute the script).

2.restart so that changes in sudoer’s file may take effect

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store