github webhook 实现代码自动部署 踩坑!! 附加git&coding webhook部署代码

本文介绍了如何配置 PHP 程序使用 Git webhook 自动更新代码。包括设置 webserver 用户免密码执行 sudo 命令、正确指定命令执行路径及通过 webhook 接收 GitHub 和 Coding.net 的推送通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

踩坑:

 

  1、php程序执行linux命令是以webserver的user用户(如apache 、www……)操作的,需要在/etc/sudoers添加用户免密码操作权限;

  %apache ALL=(ALL)       NOPASSWD:ALL
 

  2、以webserver用户执行的命令都只能在其默认根目录中进行,如apache默认根目录在/usr/share/httpd   ;nginx默认根目录在/usr/share/nginx/html;

    3、若主机配置多站点,域名指向指定目录,即用户每执行一条命令后都会返回该指定目录;

  4、git用户公钥填写root用户下.ssh生成公钥,项目部署公钥则是webserver用户下.ssh生成的公钥,如apache用户的.ssh目录在/usr/share/httpd/

 

git webhook 勾子:

<?php
//test7
class Deploy
{
    public function deploy()
    {
        $commands = ['cd /usr/share/httpd/test','git pull'];

        $signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
        $payload = file_get_contents('php://input');
        error_log($payload);
        if($this->isFromGithub($payload,$signature)){
            foreach ($commands as $command) {
                shell_exec($command);
            }
            http_response_code(200);
        }else{
            exit('error,bad request');
        }
    }

    private function isFromGithub($payload,$signature)
    {
        return 'sha1='.hash_hmac('sha1',$payload,'2e4dd3e73a4b2f854357ba21a8bdd3fc',false) === $signature;  // 2e4dd…… 就是密钥
    }
}

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $deploy = new Deploy();
    $deploy->deploy();
}
?>

 

coding webhook 勾子:

<?php
//test11
class Deploy
{
    public function deploy()
    {
        $commands = ['cd /usr/share/httpd/test','git pull'];
        $token = '2e4dd3e73a4b2f854357ba21a8bdd3fc';

        $payload = file_get_contents('php://input');
            $json = json_decode($payload,true);//error_log($payload);
        if(!empty($json['token']) && $json['token'] == $token){
            foreach ($commands as $command) {
                shell_exec($command);
            }
            http_response_code(200);
        }else{
            exit('error,bad request');
        }
    }

}
if($_SERVER['REQUEST_METHOD']== 'POST'){

    $deploy = new Deploy();
    $deploy->deploy();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值