-
第一步 在Gitlab后台设置一下
-
第二步 编写钩子文件
<?php
$path = "网站根目录";
$valid_token = '私密授权码'; //Secret Token时的字符串
$valid_ip = array('gatlab服务器ip'); //gatlab服务器ip
$client_token = $_SERVER['HTTP_X_GITLAB_TOKEN'];
$client_ip = $_SERVER['REMOTE_ADDR'];
if ($client_token !== $valid_token) die();
if (!in_array($client_ip, $valid_ip)) die();
$requestBody = file_get_contents("php://input");
if (empty($requestBody)) {
die('send fail');
}
$content = json_decode($requestBody, true);
//若是主分支且提交数大于0
if ($content['ref']=='refs/heads/master' && $content['total_commits_count']>0) {
$res = shell_exec("cd {$path} && git pull 2>&1");//以nginx用户运行
$res_log = '-------------------------'.PHP_EOL;
$res_log .= $content['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . $content['total_commits_count'] . '个commit:' . PHP_EOL;
$res_log .= $res.PHP_EOL;
file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//追加写入
}
?>
- 创建ssh模式检出的无需密码验证的操作
如果出现报错信息
Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
则使用以下命令将root权限中的ssh证书同步到www用户身份下 一般php的权限为nginx或者www
rsync -av --chown=www:www ~/.ssh /home/www/
- 最后测试 测试不通查看根目录 git-webhook.txt 日志文件