Git服务端代码自动部署

通常项目中咱们都会用到Git或者SVN等工具进行版本控制,在本地开发完后,再使用ssh链接服务器进行git pull拉取仓库代码,这里给你们分享下 如何让服务端自动拉取代码php

WebHook是什么?

官方归纳是这么说的:git

Webhooks allow you to build or set up GitHub Apps which subscribe to certain events on GitHub.com. When one of those events is triggered, we'll send a HTTP POST payload to the webhook's configured URL. Webhooks can be used to update an external issue tracker, trigger CI builds, update a backup mirror, or even deploy to your production server. You're only limited by your imagination.github

Webhooks can be installed on an organizationor a specific repository. Once installed, the webhook will be triggered each time one or more subscribed events occurs.web

翻译了一下大概的意思就是:shell

  • 经过webhooks咱们能够订阅Github.com上的某些事件(pull/push事件)
  • 触发事件后Github会向webhook配置的url发送通知

简单版

  1. 在github上建立远程仓库

建立远程仓库
建立远程仓库

  1. 初始化本地仓库并链接远程仓库json

    echo "# webhooks" >> README.md
    git init
    git add README.md
    git commit -m "first commit"
    git remote add origin https://github.com/ITHcc/webhooks.git
    git push -u origin master
    复制代码
  2. 服务器git clone远程仓库数组

    git clone 你的仓库地址服务器

  3. 添加webhooks.php脚本文件,用来接收github通知dom

    <?php
        //建议在这里验证签名
    	exec("git pull");
    复制代码
  4. 配置Webhooks通知ssh

    在仓库的Settings中选择Webhooks添加配置

  5. 测试可否通知成功

    绿色的是请求成功的,红色的是失败的

注意

  • 修改php.ini 中的disable_functions配置,删除其中的exec函数

    disable_functions配置是服务器禁用的危险函数

  • 将项目文件要与php-fpm为同一用户组不然没权限 chown -r www:www webhooks

校验签名版

打开在webhooks中配置的通知地址所对应的脚本文件,我这里配置的是 domain.com/webhooks.ph…

因此对应的脚本文件就是在我host主机根目录的webhooks.php文件,在文件中添加校验代码

<?php

//webhooks页面配置的秘钥
$key = "123456";

//接收Github发送给咱们的数据
$contents = file_get_contents("php://input");
//将json转为数组
$data = json_decode($contents);

//获取请求通中的sha1签名
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
list($algo,$hash) = explode("=",$signature);


$newHash = hash_hmac($algo,$contents,$key);

//验证本身生产的sha1与Github发给咱们的sha1是否一致
if($hash==$newHash){
    //执行git pull
    exec("git pull");

}else{
    echo "签名错误";
}
复制代码
相关文章
相关标签/搜索