这里采用的是gitlab的webhooks来实现的。
首先我们需要将服务器的ssh key添加到gitlab上
参考文章:https://www.52jingya.com/aid4091.html
如果是gitllab先安装gitlab-webhook-handler
npm install -g gitlab-webhook-handler
如果是gitlhub先安装github-webhook-handler
npm install -g github-webhook-handler
服务端使用的是nodejs来执行sh脚本,以下为node.js代码
var http = require('http')
var createHandler = require('gitlab-webhook-handler')
var handler = createHandler({ path: '/deploy', secret: 'myHashSecret' })
// 上面的 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'], function(text){ console.log(text) });
})
sh脚本为:
#!/bin/bash WEB_PATH='/home/www/nrnj-weixin' 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..." echo "Finished."
然后我们要将git项目clone到固定目录
git clone git:xxxx.git
然后在gitlab上面配置webhooks
然后输入对应的url和密码
secret token 为nodejs文件中的固定的密钥:myHashSecret
url为请求服务器的地址:假设是同一台服务器,这里为http://127.0.0.1:7777/deploy
然后推代码上去,就可以看到效果啦。
感谢您的阅读,希望对您有帮助,本文版权归 #惊讶# 所有