You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GCP Debian虚拟机上实现GitHub新提交时自动克隆仓库并执行node .命令?

实现GitHub提交后自动更新并重启Discord机器人(Debian/GCP)

1. 前置准备

先确保虚拟机环境配置完成:

  • 安装依赖工具:
    sudo apt update && sudo apt install git nodejs npm -y
    sudo npm install -g pm2
    
  • 克隆仓库并初始化机器人:
    git clone [你的仓库地址] && cd [仓库目录]
    npm install
    pm2 start index.js --name discord-bot  # 替换index.js为你的机器人入口文件
    pm2 save && pm2 startup  # 设置pm2开机自启
    

2. 编写Webhook接收服务

在机器人目录下创建webhook.js,用于监听GitHub的提交事件:

const express = require('express');
const crypto = require('crypto');
const { exec } = require('child_process');

const app = express();
const PORT = 3000;
const WEBHOOK_SECRET = '你的自定义密钥'; // 后续GitHub配置要和这个一致
const REPO_PATH = '/绝对路径/到你的仓库';
const BOT_PM2_NAME = 'discord-bot';

// 验证GitHub请求签名(防止恶意调用)
function verifySignature(req, res, next) {
  const signature = req.headers['x-hub-signature-256'];
  if (!signature) return res.status(403).send('缺少签名');

  const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
  const digest = `sha256=${hmac.update(JSON.stringify(req.body)).digest('hex')}`;

  if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest))) {
    return res.status(403).send('签名无效');
  }
  next();
}

app.use(express.json());

app.post('/webhook', verifySignature, (req, res) => {
  // 只处理push事件
  if (req.headers['x-github-event'] !== 'push') {
    return res.status(200).send('非push事件,忽略');
  }

  // 拉取最新代码
  exec(`cd ${REPO_PATH} && git pull origin main`, (pullErr, pullOut) => {
    if (pullErr) {
      console.error(`拉取失败:${pullErr}`);
      return res.status(500).send(`拉取代码失败:${pullErr}`);
    }

    // 安装新依赖(如果有更新)
    exec(`cd ${REPO_PATH} && npm install`, (installErr) => {
      if (installErr) {
        console.error(`依赖安装失败:${installErr}`);
        return res.status(500).send(`依赖安装失败:${installErr}`);
      }

      // 重启机器人进程
      exec(`pm2 restart ${BOT_PM2_NAME}`, (restartErr) => {
        if (restartErr) {
          console.error(`重启失败:${restartErr}`);
          return res.status(500).send(`重启机器人失败:${restartErr}`);
        }

        console.log('机器人已更新并重启');
        res.status(200).send('机器人更新完成');
      });
    });
  });
});

app.listen(PORT, () => {
  console.log(`Webhook服务运行在端口${PORT}`);
});

安装express依赖并启动Webhook服务:

npm install express
pm2 start webhook.js --name webhook-service

3. 配置GitHub Webhook

  1. 打开你的GitHub仓库,进入Settings > Webhooks > Add webhook
  2. 填写配置:
    • Payload URL:http://[你的GCP虚拟机公网IP]:3000/webhook(如果有域名可以用域名)
    • Content type:选择application/json
    • Secret:填写你在webhook.js中设置的WEBHOOK_SECRET
    • Which events would you like to trigger this webhook?:选择Just the push event
    • 勾选Active,点击Add webhook

4. 开放GCP防火墙端口

  1. 进入GCP控制台,找到对应虚拟机的VPC网络 > 防火墙规则
  2. 创建新规则:
    • 名称:allow-webhook-port
    • 目标:选择指定的目标标签,给你的虚拟机添加标签(比如webhook-server)
    • 来源IP范围:暂时填0.0.0.0/0(测试用,后续可限制为GitHub官方IP段)
    • 协议和端口:勾选tcp,填写3000
  3. 保存规则

5. 测试验证

修改本地代码并提交到GitHub的main分支,通过以下命令查看日志确认流程:

pm2 logs discord-bot
pm2 logs webhook-service

注意事项

  • 确保虚拟机的git有仓库访问权限:私有仓库可通过SSH密钥配置(虚拟机生成SSH公钥,添加到GitHub账户的SSH Keys中)
  • 建议将GCP虚拟机的公网IP设置为静态,避免重启后IP变更导致Webhook失效
  • 生产环境建议用Nginx反向代理配置HTTPS,替代HTTP

内容的提问来源于stack exchange,提问作者Knife worm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 15:38:12