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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM