gitlab钩子搭建

目标:在本地开发机上push代码到GitLab仓库时,通过钩子同步到测试服务器

准备工作
GitLab 服务器一台
测试服务器一台
本地开发服务器一台

1.在gitlab上新建一个项目,名称test
2.在本地机上开发克隆gitlab项目
3.在本地机上配置gitlab事件触发回调地址 (http://domain.com/Hook/hook.php)

a.建立Hooks项目
  建议目录:Hooks
             |- item1
                  |- hook.php
                  |- logs
                  |- sh
                        |- git_dev_release.sh
             |- item2

4.设置gitlab项目回调地址并进行测试

注意:需要注意的本地用户和Nginx请求用户都需要把公钥扔给测试服务器上

hook.php 代码

// 接收gitlab回调时推过来的流信息
$requestBody = file_get_contents("php://input");   
// 数据类型转换
$content = json_decode($requestBody, true);        
// 将流信息写入日志
file_put_contents("/home/xingfupeng/hooks/test/logs/test.log",var_export($content, true) . PHP_EOL,FILE_APPEND);   
// 定义执行的命令
$devSh="/bin/bash /home/xingfupeng/hooks/test/sh/git_dev_release.sh";   
if($content['ref'] == "refs/heads/dev" && $content['total_commits_count'] > 0) {
  // 当 dev 分支提交的时候且提交的文件数量大于0时才进行同步操作
  system($devSh) ;
}

git_dev_release.sh 脚本代码

LOG=/home/xingfupeng/hooks/test/logs/git_dev_release_test.log
echo "`date +%Y-%m-%d-%H:%M:%S` Begin update test code...$1..." >>$LOG
cd /home/xingfupeng/test
git checkout dev >>$LOG
git pull origin dev >>$LOG

echo "=============Start to update the test program!!!=============">> $LOG
# 同步命令操作,将本地的/home/xingfupeng/test/文件夹下的所有文件同步到测试www@192.168.20.229:/app/izhuanbei_test目录下
rsync -az --delete --exclude=.svn --exclude=.git --exclude=.gitignore --exclude=logs --exclude=cache --exclude=conf --exclude=pdf --exclude=upload --exclude=pc --exclude=wechat /home/xingfupeng/test/ www@192.168.20.229:/app/izhuanbei_test

echo "`date +"%Y-%m-%d %H:%M:%S"` SSH remote server 192.168.20.229_Server to modify config file!!!============" >> $LOG
本博客内容全部经过本人亲自测试,转载请说明转载地址
原文地址:https://www.cnblogs.com/xingfupeng/p/8484562.html