github使用Webhooks實(shí)現(xiàn)自動(dòng)化部署

參考:

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


前提:本地安裝git,服務(wù)器安裝git

這是要放到服務(wù)器上的代碼,git通過(guò)一個(gè)接口訪問(wèn)到go方法。從而實(shí)現(xiàn)git pull。我開(kāi)放的接口是 http://XXX.cn/index/index/go

public function go()
    {
        // webhook上設(shè)置的secret
        $secret = "asdf123456";
        // 校驗(yàn)發(fā)送位置,正確的情況下自動(dòng)拉取代碼,實(shí)現(xiàn)自動(dòng)部署
        $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); //最大過(guò)期時(shí)間3分鐘
                $shellPath = "/www/wwwroot/testwechat";
                $cmd = "cd $shellPath && sudo git pull";
                $res = $this -> doShell($cmd);
                print_r($res); // 主要打印結(jié)果給github記錄查看,自己測(cè)試時(shí)查看
            }
        }
    }

    /*
    * 執(zhí)行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,表明命令執(zhí)行失敗
        if ($proc == false) {
            return false;
            // do sth with HTTP response
            print_r("命令執(zhí)行出錯(cuò)!");
        } 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, // 標(biāo)準(zhǔn)輸出
            'stderr' => $stderr, // 錯(cuò)誤輸出
            'retval' => $status, // 返回值
        );

        return $data;
    }

調(diào)試:

我們可以自己訪問(wèn)一下接口。

image

以上是正確的返回

然后去github的項(xiàng)目倉(cāng)庫(kù)設(shè)置

image

通常以上設(shè)置完之后會(huì)報(bào)錯(cuò),比如返回的stderr字段

sudo: no tty present and no askpass program specified

這是最常見(jiàn)的報(bào)錯(cuò)

登錄服務(wù)器執(zhí)行的命令和shell執(zhí)行的命令權(quán)限是不同的

解決:

vim /etc/sudoers

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容