原理
- 配置gitlab,当客户端git push动作的时候,访问服务器上的一个链接比如webhook.demo.sundayle.com/webhook.php
- webhook.php会调用git_checkout.sh脚本,检测master或upload更新,就会让服务器git pull相应项目的代码到内网web目录或外网web目录。
- pull结束,我们只要重新访问内网或外网的网站就可以了。
php代码
通过 php 调用 exec函数执行shell脚本 git_checkout.sh
注:php.ini需启动exec函数。自行配置nginx。
root@demo18:/data/web/webhook# cat webhook.php1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 处理 GitLab 请求的脚本
$rowData = file_get_contents('php://input', 'r');;
$rowData = json_decode($rowData,true);
$output = '';
$type = $_GET['type'];
$domain = $_GET['domain'];
// 只拉取 master 分支的代码到测试服务器
if($rowData['ref'] == 'refs/heads/master'){
// 触发拉取代码的脚本
if('xwx' == $type){
exec("./git_checkout.sh $domain",$output);
}
logg($type." output:".json_encode($output));
}
logg($type.':'.$rowData['user_name']." commit to branch:".$rowData['ref']);
// 只拉取 upload 分支的代码到生产服务器
if($rowData['ref'] == 'refs/heads/upload'){
if('xwx' == $type){
// 触发拉取代码的脚本
exec("./upload_git_checkout.sh $domain",$output);
}
logg($type." output:".json_encode($output));
}
function logg($data){
$text = '['.date('Y-m-d H:i:s').'] '.$data."\n";
file_put_contents('./hook'.date('ym').'.log',$text,FILE_APPEND);
file_put_contents('./hook.log',$text,FILE_APPEND);
}
//http://webhook.demo.sundayle.com/webhook.php?type=xwx&domain=xxx.sundayle.com
//type=xwx 相当于认证而已
内外网shell脚本
同步内网demo服务器 shell脚本
/data/web/webhook/shell# cat git_checkout.sh1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/webserver/git/bin:$PATH
domain=$1
web_path=/data/web/$domain
if [[ $# -lt 1 ]];then
echo "Usage: ./git_checkout domain"
exit 1
fi
if [[ ! -d $web_path ]];then
cd /data/web
git clone git@git.xwx.cn:xwx/$domain.git || echo "git error"
else
cd $web_path
git reset --hard origin/master
git clean -f
git pull
git checkout master
sudo chown -R www.www $web_path
fi
同步外网服务器 shell脚本
/data/web/webhook/shell# cat shell/upload_git_checkout.sh1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/webserver/git/bin:$PATH
domain=$1
web_path=/data/web/$domain
if [[ $# -lt 1 ]];then
echo "Usage: ./git_checkout domain"
exit 1
fi
if [[ ! -d $web_path ]];then
cd /data/web
git clone git@git.xwx.cn:xwx/$domain.git || echo "git error"
else
cd $web_path
git reset --hard origin/master
git clean -f
git pull
git checkout master
sudo chown -R www.www $web_path
rsync -avu --progress -e "ssh -p25180" $web_path www@www.sundayle.com:/data/web/www.sundayle.com --log-file-format='%t %f %b' --log-file='/data/web/webhook/rsync.log'
fi
gitlab settings - integrations - url : http://webhook.demo.sundayle.com/webhook.php?type=xwx&domain=xxx.sundayle.com