跳转到主要内容

git自动化部署之webhooks的使用(php版本)

在github的webhooks中设定对应信息
设定要请求的服务器命令调用地址, 如: http://itsns.net.cn/webhooks
设定密钥key, 如: ABCDEFAAKEYM
在服务器上编写对应的命令(纯PHP代码)
编写 http://itsns.net.cn/webhooks 请求的方法如下:

<?php
// GitHub Webhook Secret.
// Keep it the same with the 'Secret' field on your Webhooks / Manage webhook page of your respostory.
$secret = "";
// 项目根目录, 如: "/var/www/webbbs"
$path = "";
// Headers deliveried from GitHub
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
if ($signature) {
  $hash = "sha1=" . hash_hmac('sha1', $HTTP_RAW_POST_DATA, $secret);
  if (strcmp($signature, $hash) == 0) {
      echo shell_exec("cd {$path} && /usr/bin/git reset --hard origin/master && /usr/bin/git clean -f && /usr/bin/git pull 2>&1");
      exit();
  }
}
http_response_code(404);

命令说明:

shell_exec("cd {$path} && /usr/bin/git reset --hard origin/master && /usr/bin/git clean -f && /usr/bin/git pull 2>&1");

/usr/bin/git reset --hard origin/master 强制恢复版本到前一个稳定版
/usr/bin/git clean -f 清理提交的更改
/usr/bin/git pull 2>&1 拉取最新的版本到本地

也可以调用本地脚本,创建shell脚本文件webhooks.sh, 并写入:

#!/bin/bash

WEB_PATH='/var/www/webbbs'
WEB_USER='nginx'
WEB_USERGROUP='nginx'

echo "Start deployment"
cd $WEB_PATH
echo "pulling source code..."
git reset --hard origin/master
git clean -f
git pull
git checkout master
echo "changing permissions..."
chown -R $WEB_USER:$WEB_USERGROUP $WEB_PATH
echo "Finished."