每次代码更新后还要手动的去把做事器上的代码也更新一遍
项目小了还好 项目大了其实摧残浪费蹂躏韶光
假如做事器上的代码也能像git那样增量更新就好了

本日就说说如何通过webhook的形式来让做事器自动拉取我们push的代码
# 事理现在的Git做事器一样平常都会有个webhook做事
什么意思呢?
便是我们在实行了push、merge等一系列的操作的时候
Git做事器会发送一个要求到我们指定的URL
并且会把这次动作的干系数据也发送过去
# 例这里我们利用开源中国的码云演示
在帮助文档中可以看到
当我们发生push之类的操作的时候
Git做事器会像我们指定的url发送以下数据
{ "before": "fb32ef5812dc132ece716a05c50c7531c6dc1b4d", "after": "ac63b9ba95191a1bf79d60bc262851a66c12cda1", "ref": "refs/heads/master", "user_id": 13, "user_name": "123", "user": { "name": "123", "username": "test123", "url": "https://gitee.com/oschina" }, "repository": { "name": "webhook", "url": "http://git.oschina.net/oschina/webhook", "description": "", "homepage": "https://gitee.com/oschina/webhook" }, "commits": [ { "id": "ac63b9ba95191a1bf79d60bc262851a66c12cda1", "message": "1234 bug fix", "timestamp": "2016-12-09T17:28:02 08:00", "url": "https://gitee.com/oschina/webhook/commit/ac63b9ba95191a1bf79d60bc262851a66c12cda1", "author": { "name": "123", "email": "123@123.com", "time": "2016-12-09T17:28:02 08:00" } } ], "total_commits_count": 1, "commits_more_than_ten": false, "project": { "name": "webhook", "path": "webhook", "url": "https://gitee.com/oschina/webhook", "git_ssh_url": "git@gitee.com:oschina/webhook.git", "git_http_url": "https://gitee.com/oschina/webhook.git", "git_svn_url": "svn://gitee.com/oschina/webhook", "namespace": "oschina", "name_with_namespace": "oschina/webhook", "path_with_namespace": "oschina/webhook", "default_branch": "master" }, "hook_name": "push_hooks", "password": "pwd"}
于是乎,我们就可以拿这些数据来做做文章了
# 准备一个git仓库安装了web做事器与git支持的做事器# 步骤# 做事器篇1.首先我们须要为www用户创建一个ssh密钥
切换到www用户下并天生一个rsa密钥
su - wwwssh-keygen -t rsa
密钥一样平常天生在 ==/var/www/.ssh/== 这个路径下
文件名为 id_rsa
创建一个可供Git做事器关照的页面网站的建立这里不再敷述
文件内容如下
<?php//git webhook 自动支配脚本//项目存放物理路径$path = "你的项目支配路径";$requestBody = file_get_contents("php://input");if (empty($requestBody)) { die('send fail');}$content = json_decode($requestBody, true);//若是主分支且提交数大于0if ($content['ref']=='refs/heads/master' && $content['total_commits_count']>0) { $res = shell_exec("cd {$path} && git pull 2>&1");//以www用户运行 $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);//追加写入}echo '很棒:'.date('y-m-d H:i:s');
以上代码相信都可以看懂
Git发送过来的数据相称丰富
我们可以用这些数据来做些过滤来决定是否须要更新做事器上确当地代码
# 代码库篇创建代码仓库创建方法这里不在敷述 2. 添加ssh密钥
在项目管理中把上面步骤第一步中得到的ssh密钥添加到仓库的支配密钥中
这样我们的web做事器就有了拉取代码的权限 3.添加hook路径
同样在项目管理中添加webhook链接
这里可以添加一个密码,我偷
须要加的话可以在hook文件中添加一个验证
可以防止被恶意访问
# 联合末了我们须要在我们的支配目录先把git初始化一次
su - wwwgit clone git仓库地址 项目支配地址
然后我们往git仓库中提交一次代码更新
稍等一下
如果统统正常的话我们的项目目录就会自动拉取你刚才提交的代码了
在hook路径中也有log记录
不须要的话可以把代码注释掉