8bq

光辉岁月

利用WebHook实现PHP自动部署Git代码

服务器

生成公钥

1
sudo -Hu www ssh-keygen -t rsa # 请选择 “no passphrase”,一直回车下去

准备钩子文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
error_reporting(1);
$target = '路径';
$token = '密钥';
$signature = $_SERVER['HTTP_X_CODING_SIGNATURE'];
$json = file_get_contents('php://input');

if (!isFromGithub($json, $token, $signature)) {
exit('error request');
}

$cmd = "cd $target && git pull";
shell_exec($cmd);

function isFromGithub($json, $token, $signature)
{
return 'sha1=' . hash_hmac('sha1', $json, $token, false) === $signature;
}

修改git配置和保存git用户名密码

1
2
3
sudo -Hu www git config --global credential.helper store # 永久保存
sudo -Hu www git config --global user.name "Bantes"
sudo -Hu www git config --global user.email "admin@xsooo.com" # 邮箱请与conding上一致

在Coding网站

添加部署公钥

复制/home/www/.ssh/id_rsa.pub的内容并添加到部署公钥

添加hook

在Coding网站上添加hook

初始化

需要先在服务器上clone一次

1
sudo -Hu www git clone https://git.coding.net/yourname/yourgit.git /home/wwwroot/website.com/ yourgit  --depth=1

注意事项

  1. sudo使用git
  2. 使用www权限
  3. php执行权限