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

踩坑:

 

  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();
}

 

posted on 2018-08-10 18:00  caigan  阅读(2078)  评论(0编辑  收藏  举报