在项目部署时,之前采用的方式是登录服务器手动去pull代码,这样做很麻烦而且在服务器管理上也存在一些风险,github和gitlab都提供有webhook功能,可以在项目发生某些变化时,系统向指定的URL发送一个POST请求
服务器搭建webhook服务,用以接收代码托管服务器发送的请求,做后续的代码更新操作。
PHP版本的服务代码如下:
+<?php // GitHub Webhook Secret. // Keep it the same with the 'Secret' field on your Webhooks / Manage webhook page of your respostory. $secret = "abc123"; // Path to your respostory on your server. // e.g. "/var/www/respostory" $path = "/data/blog"; $projects = [ 'Blog' => '/data/blog' ]; $branch = "develop"; $gitPath = "/usr/local/git/bin/"; // Headers deliveried from GitHub $giteeToken = $_SERVER['HTTP_X_GITEE_TOKEN']; $giteeEvent = $_SERVER['HTTP_X_GITEE_EVENT']; $content = file_get_contents("php://input"); $giteeObj = json_decode($content, true); $projectName = $giteeObj['project']['name']; $path = $projects[$projectName]; if ($giteeToken == $secret) { if ($giteeEvent == 'Push Hook') { $cmd = " cd {$path} && " . $gitPath . "git reset --hard origin/" . $branch . " && " . $gitPath . "git clean -f && " . $gitPath . "git pull 2>&1"; $res = shell_exec($cmd); echo $res; //exec("cd {$path} && git reset --hard origin/" . $branch . " && git clean -f && git pull 2>&1"); exit(); } } http_response_code(404);
过程中需要注意的几个地方
1、为程序执行用户(eg:www)分配git仓库的权限
2、开支php.ini 中shell_exec的支持
3、执行命令中项目路径和git的路径要用绝对路径
最后一个坑
www用户可能回去根目录去读取.ssh,如果你的ssh目录是在用户目录则会拉取失败,需要把ssh拷贝到根目录