gitlab实现提交后线上自动更新代码

环境要求:自建的gitlab,php.ini的disabled_functions 中取消shell_execphp

实现原理:跟svn的钩子相似,特定的事件git会自动触发相应的脚本.目标脚本进行相关命令执行便可.git

方法:web

第一步:在gitlab的repo中设置相关参数.若是有多个分支能够设置多个webhook.shell

以develop分支为例,若是要添加其余分支处理脚本,只须要改动$site_dir便可.json

develop.php的内容服务器

<?php
ini_set('display_errors', 'on');
    error_reporting(E_ALL);
//第一步:容许IP访问判断 这里是gitlab服务器IP
$access_ip = array('115.192.154.145');
//获取ip
$client_ip = $_SERVER['REMOTE_ADDR'];

//验证ip
if ( !in_array($client_ip, $access_ip))
{
    exit('ip error');
}


$json = file_get_contents('php://input');
$data = json_decode($json, true);
//fwrite($fs, 'Data: '.print_r($data, true).PHP_EOL);//gitlab发送过来的所有数据
//die;
if (isset($data['ref']) && $data['ref']) {
    $branch = substr($data['ref'], 11); //获取分支名称(如:refs/heads/develop)
    if (!$branch) {
        exit;
    }


    if ($branch == 'develop') {

        $site_dir='/data/sites/autoupdate-develop';
        //建立日志文件
        $logfile = './logs/test_hooks_develop_'.date('Ymd').'.log';
        $fs = fopen($logfile, 'a');
        //把请求的IP和时间写进log
        fwrite($fs, 'Request on ['.date("Y-m-d H:i:s").'] from ['.$client_ip.']'.PHP_EOL);
        fwrite($fs, '================ Update Start ==============='.PHP_EOL.PHP_EOL);
        fwrite($fs, 'Branch: '.print_r($branch, true).PHP_EOL);
        //执行shell命令并把返回信息写进日志
        try{
            $output=shell_exec("cd $site_dir && git checkout $branch && git pull origin $branch 2>&1");
            fwrite($fs, 'Info:'. $output.PHP_EOL);
            fwrite($fs,PHP_EOL. '================ Update End ==============='.PHP_EOL.PHP_EOL);
            $fs and fclose($fs);
        }catch(Exception $e){
            fwrite($fs, 'Error:'. $e->getMessage()   .PHP_EOL);
            throw new Exception("Error Processing Request", 1);
        }
        
    }
    
}else{
    exit('no data');
}
相关文章
相关标签/搜索