1. 程式人生 > >使用 Webhooks 將 Linux 伺服器上的專案自動部署到 GitHub

使用 Webhooks 將 Linux 伺服器上的專案自動部署到 GitHub

我們的專案一般都會託管在類似 Github 和 Coding 之類的平臺上,當專案部署在伺服器上之後,如果發現需要更改一處地方,需要在本地更改之後提交到 Github,然後再登入伺服器拉取 Github 上的程式碼,可以說操作非常麻煩了,我們可以使用 Github 上的 Webhooks 實現本地提交之後伺服器上自動更新。

伺服器中的操作:

2.準備鉤子檔案(假設專案的目錄為 project_dir):
建立目錄:mkdir /home/ubuntu/project_dir/public/hook  注意:這裡多了一層 public,因為我的專案是一個 Laravel 專案,入口檔案在 public 下的 index.php
修改目錄許可權: chown -R ubuntu:ubuntu /home/ubuntu/project_dir/public/hook
寫入鉤子檔案: sudo -Hu ubuntu touch /home/ubuntu/project_dir/public/index.php

檔案內容:

<?php
 
error_reporting(1);
 
$target = '/home/ubuntu/project_dir'; // 生產環境web目錄
 
$token = '您在coding填寫的hook令牌';
 
// $json = json_decode(file_get_contents('php://input'), true);  如果是application/json格式

$json = $_POST['payload'];  // 如果是application/x-www-form-urlencoded
if (empty($json['token']) || $json['token'] !== $token) { exit('error request'); }$cmd = "sudo -Hu ubuntu cd $target && git pull"; shell_exec($cmd);

3.修改 git 配置

sudo -Hu ubuntu git config --global credential.helper store # 永久儲存
sudo -Hu ubuntu git config --global user.name "hiwynn"
sudo -Hu ubuntu git config --global user.email "[email protected]" # 郵箱請與conding上一致

Github 上的操作:

1.新增部署公鑰:
複製  /home/ubuntu/webhook.pub (生成的時候我起的名字叫webhook)的內容到 Github 中的  專案 > Settings > Deplow keys > Add deploy key  中

2.新增 Webhooks:
專案 > Settings > Webhooks > Add webhook

3.如果成功的話這裡是個綠色的對號,不成功的話是個紅色的歎號。如果不成功的話檢查一下各項配置,更改之後點選  Redeliver  重新發送試試。