使用Github或Gitlab的Webhooks实现代码自动更新部署(Ubuntu20.04)

1、安装ssh服务
root@Ubuntu:~# apt-get install openssh-server

2、部署php
root@Ubuntu:~# add-apt-repository ppa:ondrej/php
root@Ubuntu:~# apt-get update
root@Ubuntu:~# apt-get install php-fpm php-mysql php-curl php-json php-zip php-dev  # php-dev可选
root@Ubuntu:~# /etc/init.d/php7.4-fpm start

3、部署nginx
root@Ubuntu:~# apt-get install nginx

4、配置nginx支持php
root@Ubuntu:~# vim /etc/nginx/sites-enabled/default

location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    
    #    # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    #    # With php-cgi (or other tcp sockets):
    #    fastcgi_pass 127.0.0.1:9000;
    }

location /webhook {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}

5、创建php测试文件
root@Ubuntu:/var/www/html# vim index.php

<?php phpinfo(); ?>

6、创建php脚本(注意:html目录权限要设置为777)
root@Ubuntu:/var/www/html# vim script.php  (与gitlab webhook对接)

<?php
//$valid_token = 'secret_token';
//$client_token = $_SERVER['HTTP_X_GITLAB_TOKEN'];
//if ($client_token !== $valid_token) die('<br />Token mismatch!');
echo $_SERVER['REMOTE_ADDR'];
$valid_ip = array('127.0.0.1'); //这里填你的gitlab服务器ip
$client_ip = $_SERVER['REMOTE_ADDR'];
if (!in_array($client_ip, $valid_ip)) die('<br />Ip mismatch!');
exec("cd /var/www/html/;mkdir phptest");
//exec("cd /var/www/html/; git pull origin master 2>&1", $output);
//var_dump($output); 这样可以用浏览器调试输出
?>
root@Ubuntu:/var/www/html# vim script.php    (与github webhook对接)
<?php
date_default_timezone_set("Asia/Shanghai");

// 填写自己项目根目录绝对路径
$applicationPath = "/var/www/html/game/public";
// 这里是在 github webhooks页面设置的 Secret
$secret = "project";

// 获取github webhooks 请求头中的签名
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
if (!$signature) {
   return http_response_code(404);
}

// github webhooks 请求体 Payload 内容
$payloadJson = file_get_contents("php://input");
$content = json_decode($payloadJson, true);
list($algo, $hash) = explode("=", $signature, 2);

// 组装 webhooks 请求信息
$pushInfo = "{$content['head_commit']['author']['name']} 在 " . date('Y-m-d H:i:s') . PHP_EOL;
$pushInfo .= "向 {$content['repository']['name']} 项目的 {$content['ref']} 分支 " .PHP_EOL;
$pushInfo .= "push 了 " . count($content['commits']) . " 个commit: " . PHP_EOL;

// 验签
$payloadHash = hash_hmac($algo, $payloadJson, $secret);
if ($hash === $payloadHash) {
    $ret = shell_exec("cd {$applicationPath} && sudo git pull origin main");
    $responseLog = "Success: " . PHP_EOL;
    $responseLog .= $pushInfo . $ret . PHP_EOL . PHP_EOL;
} else {
    $responseLog  = "Error: " . PHP_EOL;
    $responseLog .= "{$pushInfo} 验签失败" . PHP_EOL . PHP_EOL;
}

// 输出响应内容,可在 github webhooks - Recent Deliveries 中的 Response Body 中查看 
echo $responseLog;

// 记录 webhooks 请求日志
file_put_contents("/tmp/webhooks.log", $responseLog);
?>

7、配置sudo
root@project:~# visudo

# User privilege specification
root    ALL=(ALL:ALL) ALL
www-data ALL=(ALL:ALL) NOPASSWD:/usr/bin/git

8、访问http://127.0.0.1/script.php执行脚本

9、Nginx日志出现"Access to the script '/var/www/html/webhook' has been denied (see security.limit_extensions)"错误解决办法
1、修改配置文件中security.limit_extensions选项为空
root@Ubuntu:~# vim /etc/php/7.4/fpm/pool.d/www.conf

398 ; Limits the extensions of the main script FPM will allow to parse. This can
399 ; prevent configuration mistakes on the web server side. You should only limit
400 ; FPM to .php extensions to prevent malicious users to use other extensions to
401 ; execute php code.
402 ; Note: set an empty value to allow all extensions.
403 ; Default Value: .php
404 ;security.limit_extensions = .php .php3 .php4 .php5 .php7
405 security.limit_extensions =

2、修改php.ini文件中选项cgi.fix_pathinfo=1
root@Ubuntu:~# vim /etc/php/7.4/fpm/php.ini

791 ; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
792 ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
793 ; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
794 ; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
795 ; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts
796 ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
797 ; http://php.net/cgi.fix-pathinfo
798 cgi.fix_pathinfo=1

参考链接:
       https://www.jianshu.com/p/00bc0323e83f
       https://www.cnblogs.com/-wenli/p/13420106.html       # python webhook
       https://qq52o.me/2482.html
       https://www.jianshu.com/p/bab37843abc7

posted @ 2022-07-11 13:47  風£飛  阅读(308)  评论(0编辑  收藏  举报