緣起
最近用Gatsby 寫了一個個人blog,link => http://new.ruoduan.cn/
Github 🙏🙏🙏 Star
發現 build
後體積太大,FTP 發文件 都要10幾分鐘,挑選來下自動化部署工具🔧,本打算用jenkins
感覺有點重,而且學習成本較高。
看了一下覺得 使用 github的webHooks 是最合適的
Graph
大致流程是這樣的:👇
- 話不多說直接上代碼 代碼分爲三個部分
- Nodejs => Server
- Shell 腳本
- 插件
install
我的環境是 CentOS
服務器 應具備 nodejs && git
- 首先先安裝 github-webhooks的插件和pm2
服務器上
npm install -g github-webhook-handler pm2
nodejs 服務
webhooks.js
var http = require('http')
// github-webhook-handler 的絕對路徑
var createHandler = require('/usr/lib/node_modules/github-webhook-handler')
var handler = createHandler({ path: '/', secret: 'xxx' })
// 上面的 secret 保持和 GitHub 後臺設置的一致
function run_cmd(cmd, args, callback) {
var spawn = require('child_process').spawn;
var child = spawn(cmd, args);
var resp = "";
child.stdout.on('data', function(buffer) { resp += buffer.toString(); });
child.stdout.on('end', function() { callback (resp) });
}
http.createServer(function (req, res) {
handler(req, res, function (err) {
res.statusCode = 404
res.end('no such location')
})
}).listen(7777) // 啓動服務的端口,需要開放安全組
handler.on('error', function (err) {
console.error('Error:', err.message)
})
handler.on('push', function (event) {
console.log('Received a push event for %s to %s',
event.payload.repository.name,
event.payload.ref);
run_cmd('sh', ['./webhooks.sh',event.payload.repository.name], function(text){ console.log(text) });
})
shell
webhooks.sh
#!/bin/bash
WEB_PATH='/root/githubWebhook/warehouse/my-Gatsby-Blog'
echo "開始執行shell"
cd $WEB_PATH
echo "pulling source code..."
git pull
echo "changing permissions..."
#chown -R $WEB_USER:$WEB_USERGROUP $WEB_PATH
echo " git pull 完成. 開始 build"
yarn run gatsby build
echo "build 完成"
到這裏 我們服務端
需要準備的東西就差不多了 Nginx 就不放出來
Github Settings
放一張圖吧
start
接下來 pm2 啓動服務
pm2 start webhooks.js -o ./webhooks.log
寫在最後
接下來 我還會更新一篇 長文 Gatsby 的文章 詳細指出 其中的利弊,無論你是 新手還是想使用現代框架 ——— React 來維護我自己的blog 的老手 都非常適合
我的 New Blog => http://new.ruoduan.cn/
年後想換個工作,求內推!求內推!求內推! Live:杭州
我的一些信息 可查看我的 Blog about 部分 http://new.ruoduan.cn/about