GitHub利用webhook實現push時項目自動部署

在網站根目錄下放置 webhook.php 自動部署文件,而後GitHub服務器的對應項目的 webhooks 配置上該文件的網址(Payload URL)與 密鑰(Secret),需啓用php的shell_exec函數。 輸入圖片說明php

webhook.php 代碼git

<?php


    $target = '/home/www/im'; // 生產環境web目錄
    //密鑰
    $secret = "123456";
    $wwwUser = 'www';
    $wwwGroup = 'www';

    //日誌文件地址
    $fs = fopen('../storage/logs/gitHubAuto_hook.log', 'a');

    //獲取GitHub發送的內容 
    $json = file_get_contents('php://input');
    $content = json_decode($json, true);
    //github發送過來的簽名  
    $signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];

    if (!$signature) {
       fclose($fs);
       return http_response_code(404);
     }

    list($algo, $hash) = explode('=', $signature, 2);
    //計算簽名  
    $payloadHash = hash_hmac($algo, $json, $secret);

    // 判斷簽名是否匹配  
    if ($hash === $payloadHash) {
        $cmd = "cd $target && git pull";
        $res = shell_exec($cmd);

        $res_log .= 'Success:'.PHP_EOL;
        $res_log .= $content['head_commit']['author']['name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '項目的' . $content['ref'] . '分支push了' . count($content['commits']) . '個commit:' . PHP_EOL;
        $res_log .= $res.PHP_EOL;
        $res_log .= '======================================================================='.PHP_EOL;

        fwrite($fs, $res_log);
        $fs and fclose($fs);


      } else {
            $res_log  = 'Error:'.PHP_EOL;
            $res_log .= $content['head_commit']['author']['name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '項目的' . $content['ref'] . '分支push了' . count($content['commits']) . '>個commit:' . PHP_EOL;
            $res_log .= '密鑰不正確不能pull'.PHP_EOL;
            $res_log .= '======================================================================='.PHP_EOL;
           fwrite($fs, $res_log);
           $fs and fclose($fs);
      }
相關文章
相關標籤/搜索