ubuntu Gitlab 利用webhook实现push时项目自动部署
前提:已经安装git
本次服务环境是 lamp apache运行用户是www-data
- 在gitlab创建一个普通用户,加入到目标项目里的成员里,只需要有pull权限即可
- 在生产服务器上为www-data用户生成 SSH 公钥,路径一般在在apache的根目录,把生成的公钥 id_rsa.pub 复制粘贴到Git服务器上第一步里的普通用户的ssh公钥里
sudo -u www ssh-****** - 首次从git服务器上抓取资源用clone,指定目录需要为空:
sudo -u www-data git clone [email protected]:xxx/xxx.git
4.先cd到项目根目录,后续再抓取直接pull ; 模拟www-data用户身份执行:
sudo -u www-data git pull
5.网站根目录下放置 git-webhook-handler.php 自动部署文件,然后Git服务器的对应项目的 webhooks 配置上该文件的网址(Push events),需启用php的shell_exec函数。
自动部署文件 git-webhook-handler.php 代码如下:
<?php
//git webhook 自动部署脚本
//项目存放物理路径
$path = "/home/www/ceshi/";
$requestBody = file_get_contents("php://input");
$token = $_SERVER['HTTP_X_GITLAB_TOKEN'];
if ($token != "cc17c30cd111c7215fc8f51f8790e0e1") {
//$res_log .= "token is error".PHP_EOL;
//file_put_contents("git-webhook-ceshi.txt", date("Y-m-d H:i:s"), FILE_APPEND);//追加写入
//file_put_contents("git-webhook-ceshi.txt", $res_log, FILE_APPEND);//追加写入
die();
}
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");//以www用户运行
$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-ceshi.txt", $res_log, FILE_APPEND);//追加写入
}
http://www.piaoyi.org/linux/Gitlab-GitHub-webhook-push-auto-deployment.html