在gitlab 中使用webhook 實現php 自動部署git 代碼

在技術團隊討論中,咱們決定從svn 遷移到 git ,因而使用了gitlab,代碼自動部署使用了webhookphp

在服務器上

1.開啓PHP須要的環境支持

服務器環境必須先安裝git 環境,webhook 依賴php運行環境,同時須要使用shell_exec 和 exec 等函數。使用前先開啓php部分可執行函數。html

$ which php
/usr/local/php/bin/php

$ sudo vi /usr/local/php/etc/php.ini


;disable_functions = passthru,exec,system,chroot,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket,popen

2.查看nginx 運行用戶

由於gitlab 的 webhooks 的使用者都是web 服務器在用,我使用的是nginx ,因此必須的知道nginx和php-fpm的全部者是誰linux

$ ps aux | grep php

$ ps aux | grep php-fpm

個人環境下是nginxnginx

3.生成部署公鑰

sudo -Hu nginx ssh-keygen -t ras #一路回車下去就能夠了

而後把公鑰添加到gitlab 上去,不要問我怎麼添加的,若是使用過github,就應該知道這個是怎麼回事git

4.首次從gitlab clone,指定目錄須要爲空

git clone git@git.xxxx.com:test/test.git  /data/www/git_test/

在網站根目錄下放置webhook 自動部署文件webhook.php,而後gitlab 對應項目的webhook 配置使用該文件的網址

<?php
//git webhook 自動部署腳本
//項目存放物理路徑
$path = "/data/www/git_test/test/";

$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);//追加寫入
    
}

修改這個文件的全部者爲 nginxgithub

chown -R nginx:nginx webhook.php

參考文章
1.http://www.piaoyi.org/linux/G...
2.https://docs.gitlab.com/ce/us...
3.https://m.aoh.cc/149.htmlweb

相關文章
相關標籤/搜索