webhook 自动部署

原理
  1. push代码到github的时候,github会监听push动作
  2. 然后就会访问github中webhook配置的url,如:https://xxx.com/webhook.php
  3. webhook.php中的代码会在服务器中git pull相应的代码到web目录中
配置

1662266160062.jpg

如果回调成功了会返回Response 200.

webhook.php 脚本实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
//git webhook 自动部署脚本
//接收数据
$requestBody = file_get_contents("php://input");
if (empty($requestBody)) {
die('send fail');
}
$content = json_decode($requestBody, true); //数据转换
//若是主分支且提交数大于0
if ($content['ref'] == 'refs/heads/master') {
//PHP函数执行git命令
$res = shell_exec('cd /root/www/project && git pull 2>&1);
$res_log = '-------------------------'.PHP_EOL;
$res_log .= ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push'.$res;
//将每次拉取信息追加写入到日志里
file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);
}

给回调程序加上执行权限

1
chmod 755 webhook.php
各种坑
  1. git pull失败原因
  • 权限问题,nginx是www用户,.git文件是root创建的,www对.git没有访问权限,需要修改.git文件的用户和组。
  • ssh密钥是root用户创建的,www也没有访问权限,需要切换www用户重新生成ssh密钥。