Operations 7 min read

Automate Test Deployments with GitLab Webhooks and Apache

This guide explains how to configure GitLab webhooks and an Apache endpoint to automatically pull code updates to a test server after each commit, covering server setup, SSH key configuration, PHP interface script, and troubleshooting steps.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Automate Test Deployments with GitLab Webhooks and Apache

Hooks

Git provides a mechanism to run custom scripts before or after specific events, similar to event listeners or triggers. Git Hooks are scripts that are triggered after events such as commit, push, receive, etc.

GitLab’s web hooks work similarly: when a project receives a commit, tag, or other action, GitLab can call a URL to perform actions such as updating code.

Purpose of Configuration

Because the system is a backend interface, after developers push to the Git repository we need to automatically deploy to the test environment, which requires GitLab web hooks for automatic updates.

Client: test server IP 192.168.1.2

Server: GitLab server IP 192.168.1.1

GitLab Version: 7.13.0.pre

GitLab‑Shell Version: 2.6.3

1. Configure an Apache virtual host on the client to expose a web‑hook endpoint.

#vim /usr/local/apache/conf/httpd.conf

listen 81
<VirtualHost *:81>
      ServerAdmin localhost
      DocumentRoot "/www/gitlab_web"
      <Directory "/www/gitlab_web">
            Options -Indexes +FollowSymLinks
            AllowOverride None
            Order allow,deny
            Allow from all
      </Directory>
      RewriteEngine on
</VirtualHost>

2. On the GitLab server, create a new user for the client and add its public SSH key to the user’s profile (Settings → SSH Keys).

#su - webuser
#ssh-keygen -t rsa
#cd /path/project
#git clone [email protected]:test/test_api.git

3. Add the PHP interface file on the client.

#vim /www/gitlab_web/index.php

<?php
$valid_token = 'd49dfa762268687eb2ca59498ce852';
$valid_ip = array('192.168.1.1','10.17.10.175','112.112.112.112');
$client_token = $_GET['token'];
$client_ip = $_SERVER['REMOTE_ADDR'];
$fs = fopen('./auto_hook.log', 'a');
fwrite($fs, 'Request on ['.date("Y-m-d H:i:s").'] from ['.$client_ip.']'.PHP_EOL);
if ($client_token !== $valid_token) {
    echo "error 10001";
    fwrite($fs, "Invalid token [{$client_token}]".PHP_EOL);
    exit(0);
}
if (!in_array($client_ip, $valid_ip)) {
    echo "error 10002";
    fwrite($fs, "Invalid ip [{$client_ip}]".PHP_EOL);
    exit(0);
}
$json = file_get_contents('php://input');
$data = json_decode($json, true);
fwrite($fs, 'Data: '.print_r($data, true).PHP_EOL);
fwrite($fs, '======================================================================='.PHP_EOL);
$fs and fclose($fs);
// exec("/bin/sh /root/updategit.sh");
exec("cd /path/project;/usr/bin/git pull");
?>

4. Test the endpoint:

http://192.168.1.2:81/?token=d49dfa7622681425fbcbdd687eb2ca59498ce852

5. View the client log:

#cat /www/gitlab_web/auto_hook.log
=======================================================================
Request on [2015-07-03 14:05:02] from [112.122.112.112]
Data:
=======================================================================

6. Add the web hook in GitLab (Admin Area → Projects → test → Settings → Web Hooks → Add Web Hook).

7. Push changes to the GitLab repository and verify that the test environment updates.

#cat /www/gitlab_web/auto_hook.log
Request on [2015-07-03 14:13:37] from [12.123.12.3]
Data: Array
(
    [object_kind] => push
    [before] => e5988b5dce7a038
    [after] => d8ce92ac4ab4ba046dd
    [ref] => refs/heads/master
    [checkout_sha] => d8ceefd5c4ab4ba046dd
    [message] => 
    [user_id] => 7
    [user_name] => test
    [user_email] => [email protected]
    [project_id] => 3
    [repository] => Array
        (
            [name] => test_api
            [url] => [email protected]:test/test.api
            [description] => test.com product code
            [homepage] => http://xx./test_api
            [git_http_url] => http://xx./test_api
            [git_ssh_url] => [email protected]:test.git
            [visibility_level] => 10
        )
    [commits] => Array
        (
            [0] => Array
                (
                    [id] => d8cec4ab4ba046dd
                    [message] => 测试gitlab的web hook接口。
                    [timestamp] => 2015-07-03T14:13:51+08:00
                    [url] => http://xxxx/test_api/commit/d8ce95c4ab4ba046dd
                    [author] => Array
                        (
                            [name] => test
                            [email] => [email protected]
                        )
                )
        )
    [total_commits_count] => 1
)

Precautions

1. If the endpoint does not trigger automatic updates, verify that the Apache user can execute the commands successfully.

#su - webuser
#cd /path/project
#git pull

2. If the Apache user cannot run commands or update the Git repository, check the shell assigned to the Apache user.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationDeploymentGitLabApacheWebhooks
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.