github使用Webhooks實現自動化部署


參考:

  https://blog.csdn.net/u013764814/article/details/85240752

--------------------------------------------

前提:本地安裝git,服務器安裝git

這是要放到服務器上的代碼,git通過一個接口訪問到go方法。從而實現git pull。我開放的接口是 http://XXX.cn/index/index/go

public function go()
    {
        // webhook上設置的secret
        $secret = "asdf123456";
        // 校驗發送位置,正確的情況下自動拉取代碼,實現自動部署
        $signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
        if($signature) {
            $hash = "sha1=".hash_hmac('sha1', file_get_contents("php://input"), $secret);
            if (strcmp($signature, $hash) == 0) {
                set_time_limit(3 * 60); //最大過期時間3分鍾
                $shellPath = "/www/wwwroot/testwechat";
                $cmd = "cd $shellPath && sudo git pull";
                $res = $this -> doShell($cmd);
                print_r($res); // 主要打印結果給github記錄查看,自己測試時查看
            }
        }
    }

    /*
    * 執行shell命令
    */
    protected function doShell ($cmd, $cwd = null) {
        $descriptorspec = array(
            0 => array("pipe", "r"), // stdin
            1 => array("pipe", "w"), // stdout
            2 => array("pipe", "w"), // stderr
        );
        $proc = proc_open($cmd, $descriptorspec, $pipes, $cwd, null);
        // $proc為false,表明命令執行失敗
        if ($proc == false) {
            return false;
            // do sth with HTTP response
            print_r("命令執行出錯!");
        } else {
            $stdout = stream_get_contents($pipes[1]);
            fclose($pipes[1]);
            $stderr = stream_get_contents($pipes[2]);
            fclose($pipes[2]);
            $status = proc_close($proc); // 釋放proc
        }
        $data = array(
            'stdout' => $stdout, // 標准輸出
            'stderr' => $stderr, // 錯誤輸出
            'retval' => $status, // 返回值
        );

        return $data;
    }

 

調試:

  我們可以自己訪問一下接口。

  

以上是正確的返回

 

然后去github的項目倉庫設置

 

 

通常以上設置完之后會報錯,比如返回的stderr字段

sudo: no tty present and no askpass program specified

 這是最常見的報錯

登錄服務器執行的命令和shell執行的命令權限是不同的

解決:

 # vim /etc/sudoers

 


免責聲明!

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



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