Gitlab 服务器代码钩子自动更新

1 篇文章 0 订阅
1 篇文章 0 订阅
  1. 第一步 在Gitlab后台设置一下
    找到系统的设置在这里插入图片描述

  2. 第二步 编写钩子文件

<?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);//追加写入
        
    }
?>
  1. 创建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/
  1. 最后测试 测试不通查看根目录 git-webhook.txt 日志文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值