github webhook自动化部署

本文介绍如何使用Node.js创建GitHub webhook处理器,通过监听GitHub仓库的push和issues事件,实现自动化部署和事件通知。文章详细展示了配置过程、代码实现及关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务端nodejs监控

secret在github上设置的,path为访问路径:如在github上设置Payload Url :xxxx/webhook

监控

首先下载cnpm i github-webhook-handler

var http = require('http')
var createHandler = require('github-webhook-handler')
var handler = createHandler({ path: '/webhook', secret: '123456' })

function RunCmd (cmd, args, cb) {
  var spawn = require('child_process').spawn;
  var child = spawn(cmd, args);
  var result = '';
  child.stdout.on('data', function (data) {
    result += data.toString();
  });
  child.stdout.on('end', function () {
    cb(result)
  });
}

http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404;
    res.end('no such location');
  })
}).listen(8098)

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);
//监听来自deploy分支,然后部署
  if (event.payload.ref.includes('deploy')) {
    var shpath = './deploy.sh';//下方代码
    RunCmd('sh', [shpath], function (result) {
      console.log(result);
    })
  }
})

handler.on('issues', function (event) {
  console.log('Received an issue event for %s action=%s: #%d %s',
    event.payload.repository.name,
    event.payload.action,
    event.payload.issue.number,
    event.payload.issue.title);
})

拉取代码deploy.sh

拉取之前,在github=>settings=>Deploy key设置好秘钥

提示:最好使用ssh拉取代码,否则会出现其他问题

#! /bin/bash
echo '开始执行'
cd Airport-Management-System
# git init
# git remote add origin 仓库地址
git fetch
echo '切换分支'
git checkout deploy
## 拉取最新代码
echo '开始拉去最新代码'
git pull origin deploy
cp -rf /usr/local/auto-build/Airport-Management-System/dist/* /usr/local/nginx/airport
echo '拷贝完成'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值