本文大部分內容來自https://www.lovelucy.info/auto-deploy-website-by-webhooks-of-github-and-gitlab.html
本文對任何提供Webhook的git倉庫都適用
2016-06-29_14635623250348.jpg
首先完成Node.js服務器的代碼構建,先上代碼猾担,再解釋
var http = require('http')
var createHandler = require('github-webhook-handler')
var handler = createHandler({ path: '/', secret: 'root' })
// 上面的 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', ['./deploy.sh',event.payload.repository.name], function(text){ console.log(text) });
})
上面的代碼中用到了一個github-webhook-handler
的中間價袭灯,你可以用npm install -g github-webhook-handler
來全局安裝
還有代碼這行:
var handler = createHandler({ path: '/', secret: 'root' })
其中secret后的參數(shù)是你在github的項目中添加webhook時設置的secret值,替換成自己的就行了
完成deploy.sh腳本
deploy.sh腳本負責進入項目的目錄绑嘹,然后利用git命令拉取最新的代碼稽荧,還是直接貼代碼:
#!/bin/bash
WEB_PATH='/root/tools/'$1
WEB_USER='root'
WEB_USERGROUP='root'
echo "Start deployment"
cd $WEB_PATH
echo "pulling source code..."
git reset --hard origin/master
git clean -f
git pull
git checkout master
echo "changing permissions..."
chown -R $WEB_USER:$WEB_USERGROUP $WEB_PATH
echo "Finished."
deploy.sh 會接受第一個參數(shù)當做項目名字,然后進入這個項目的目錄執(zhí)行git操作工腋,這個參數(shù)是在deploy.js中根據(jù)hook返回的項目名字來的姨丈,代碼應該比較容易懂,都是些簡單的git命令擅腰。
如果是全新的項目蟋恬,需要在你的服務器上先clone要部署的項目
你需要根據(jù)自己的實際項目位置,修改WEB_PATH的值
后臺運行deploy.js
利用Linux提供的nohup命令趁冈,讓deploy.js運行在后臺
nohup node deploy.js > deploy.log &
去Github后臺添加webhook
進入你需要自動部署的項目的github地址歼争,進入項目的設置頁面,點擊左側的Webhooks & services
2016-06-29_14635620989191.jpg