利用git webhook请求php脚本,触发deployer自动部署实现的核心流程:PC/Client(git push) => GitHub/Git Repository(webhook/http request) => Server/WebHost(php hook/shell_exec) => Server/WeHost(deploy commands)

设置部署公钥

部署脚本执行的用户www-data,把www-data的公钥添加到仓库的部署公钥里以便ssh访问git更新代码。

Deployer部署配置

安装deployer

参考Deployer文档 - 安装

配置deployer

生成配置文件

dep init

详细参考Deployer文档 - 配置

<?php
namespace Deployer;
require 'recipe/laravel.php';

// Configuration
set('ssh_type', 'native');
set('ssh_multiplexing', true);
set('repository', 'git@git.oschina.net:maoxuner/pandora.git');
set('branch', 'geeka');
add('shared_files', []);
add('shared_dirs', []);
add('writable_dirs', []);

// Servers
localServer('sunny', 'localhost')
    ->set('deploy_path', '/var/www/geeka')
    ->pty(true);

// Tasks
desc('Set Environment');
task('setEnv', function () {
    run("cp {{deploy_path}}/release/.env.testing {{deploy_path}}/release/.env");
    run("php {{deploy_path}}/release/artisan key:generate");
});
after('deploy:vendors', 'setEnv');

// [Optional] if deploy fails automatically unlock.
after('deploy:failed', 'deploy:unlock');

// Migrate database before symlink new release.
before('deploy:symlink', 'artisan:migrate');

WebHooks

不同Git仓库,webhook发送的数据不同,这里以Git@OSC为例。

php脚本

www-data对目录应具有写入权限,否则得注释日志记录的相关代码。建议把该文件放在根目录以外的目录,并配置别名,这样自动部署的时候不会影响到该文件。

<?php
$password = 'hook password';    // 钩子密码,用来防止恶意访问
$branch = 'master';             // 部署分支,用来过滤其他分支的推送消息

$postStr = file_get_contents("php://input");
$fh = fopen('deploy.log', 'a');
fwrite($fh, $postStr."\n");

$data = json_decode($postStr);
if($data && property_exists($data, 'password')){
    if($data->password == $password && $data->ref == 'refs/heads/'.$branch){
        $result = shell_exec('dep deploy');
        fwrite($fh, $result."\n");
    }
}

fwrite($fh, date('Y-m-d H:i:s')."\n-------- 分 -- 割 -- 线 --------\n\n");
fclose($fh);

Git仓库设置

添加一个webhook,URL地址为以上php脚本的地址,并设置好密码。

利用git hook自动部署

目测是以WebHost作为git仓库,并通过仓库本身来执行shell脚本,实现自动部署。参考使用 Git Hook 实现网站的自动部署

参考文章