2018年第一篇文章,没啥技术含量,权当笔记php
咱们通常都会用git或者svn来管理咱们的代码git
每次代码更新后还要手动的去把服务器上的代码也更新一遍web
项目小了还好 项目大了着实浪费时间shell
要是服务器上的代码也能像git那样增量更新就行了json
今天就说说如何经过webhook的形式来让服务器自动拉取咱们push的代码服务器
如今的Git服务器通常都会有个webhook服务ssh
什么意思呢?svn
就是咱们在执行了push、merge等一系列的操做的时候网站
Git服务器会发送一个请求到咱们指定的URLurl
而且会把这次动做的相关数据也发送过去
这里咱们使用开源中国的码云演示
在帮助文档中能够看到
当咱们发生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" }
因而乎,咱们就能够拿这些数据来作作文章了
1.首先咱们须要为www用户建立一个ssh密钥
切换到www用户下并生成一个rsa密钥
su - www ssh-keygen -t rsa
密钥通常生成在 ==/var/www/.ssh/== 这个路径下
文件名为 id_rsa
网站的创建这里再也不敷述
文件内容以下
<?php //git webhook 自动部署脚本 //项目存放物理路径 $path = "你的项目部署路径"; $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");//以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发送过来的数据至关丰富
咱们能够用这些数据来作些过滤来决定是否须要更新服务器上的本地代码
建立方法这里不在敷述
在项目管理中把上面步骤第一步中获得的ssh密钥添加到仓库的部署密钥中
这样咱们的web服务器就有了拉取代码的权限
3.添加hook路径
一样在项目管理中添加webhook连接
这里能够添加一个密码,我偷懒这里没加
须要加的话能够在hook文件中添加一个验证
能够防止被恶意访问
最后咱们须要在咱们的部署目录先把git初始化一次
su - www git clone git仓库地址 项目部署地址
而后咱们往git仓库中提交一次代码更新
稍等一下
若是一切正常的话咱们的项目目录就会自动拉取你刚才提交的代码了
在hook路径中也有log记录
不须要的话能够把代码注释掉