2020年前端必须掌握的自动化部署(webhooks)

缘起

最近用Gatsby 写了一个我的blog,link => new.ruoduan.cn/node

Github 🙏🙏🙏 Stargit

发现 build 后体积太大,FTP 发文件 都要10几分钟,挑选来下自动化部署工具🔧,本打算用jenkins 感受有点重,并且学习成本较高。 看了一下以为 使用 github的webHooks 是最合适的github

Graph

大体流程是这样的:👇web

webHooks自动化部署

  • 话很少说直接上代码 代码分为三个部分
  1. Nodejs => Server
  2. Shell 脚本
  3. 插件

install

个人环境是 CentOSshell

服务器 应具有 nodejs && gitnpm

  • 首先先安装 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.shbash

 #!/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

放一张图吧框架

ithub Settings

start

接下来 pm2 启动服务

pm2 start webhooks.js -o ./webhooks.log

pm2的一些基本命令

写在最后

接下来 我还会更新一篇 长文 Gatsby 的文章 详细指出 其中的利弊,不管你是 新手仍是想使用现代框架 ——— React 来维护我本身的blog 的老手 都很是适合

个人 New Blog => new.ruoduan.cn/

年后想换个工做,求内推!求内推!求内推! Live:杭州

个人一些信息 可查看个人 Blog about 部分 new.ruoduan.cn/about

相关文章
相关标签/搜索