Didn't you learn how to deploy front-end automation since 9102?

Preface

  • The earliest way: After the front end has written the code, it builds locally and uploads the file to the server through the server xftp or ftp for updating.
  • After using Git: The server pulls the latest code from the repository through the git clone project by executing git pull origin [branch] in the root directory of the project
  • Automated deployment: After configuring WebHook and server: the project is packaged and submitted to the code base, and the server automatically pulls the latest code from the git repository

The underlying implementation principle:

  • Fill in the url of the server where GitHub configures the webhook. Every time push code goes to github, GitHub sends a request to the url in the webhook.
  • After receiving the request, the server executes the local bash script after verification, and writes the command to pull the code from github.

  • Use environment: Centos7.*, Node, Git
  • Code base platform: Gitee / Github
  • Tips: Different operating environments can be configured and implemented

Process description

  • I. Configuring WebHook in the github project
  • 2. Configure server, add Node project, run project

Configuration of WebHook

1.1 Enter the code base to configure the webhook interface

Take github for example

Log in GitHub - > Enter repository - > find settings - > enter webhook

  • This is the configured webhook
  • Click on the new webhook

  • Now that the webhook in github is configured successfully, configure the server

II. Configuring Servers

Configuration environment

  1. Download git, Node environment
  2. Create a Node project, preferably saved in the code base
  • For reference web-hook This is a server-side Node project demo

Using Node to write Automated Deployment scripts

Reference resources web-hook

1. Create server.js to listen on a port

server.js

const http = require('http') // http module
const { spawn } = require('child_process') // Subprocesses used to execute scripts
const { PORT, SECRET } = require('./src/config') // configuration file
const { sign } = require('./src/utils') // Tool files
const { resultString } = require('./src/resModel') // The server returns JSON

const server = http.createServer((req, res) => {
  // Print in request
  console.log(`--- ${req.method} --- ${req.url} ---`)
  // Set header to json format
  res.setHeader('Content-Type', 'application/json')

  if (req.method === 'POST' && req.url === '/webhook') {
    // post /webhook are all requests for github
    console.log('--- Hit webhook ---')
    // Getting body
    let buffers = []
    req.on('data', buffer => {
      buffers.push(buffer)
    })
    req.on('end', () => {
      let body = Buffer.concat(buffers)
      // Get the field of event in header, github for push, gitee for Push Hook
      let event = req.headers['x-github-event'] || req.headers['x-gitee-event']
      console.log(`--- Event Name: ${event}  ---`)
      if (req.headers['user-agent'] === 'git-oschina-hook') {
        // gitee
        console.log('--- Gitee platform ---')
        // SECRET is configured in config.js
        if (req.headers['x-gitee-token'] === SECRET) {
          if (event === 'Push Hook') {
            console.log('--- push Mission hit ---')
            let payload = JSON.parse(body)
            console.log(
              `--- Task Name: ${payload.repository.name}, Route: ${payload.repository.path} ---`
            )
            // Open subprocesses to execute corresponding scripts
            // payload.repository.path is the repo path from gitee/github
            // Execute the script in sh directory by the value of path
            // For example, the value of the project name web_hook path is web_hook
            // The script to execute is. / sh/web_hook.sh
            let child = spawn('sh', [`./sh/${payload.repository.path}.sh`])
            // Receiving data from subprocesses
            let buffers = []
            child.stdout.on('data', buffer => {
              console.log(`--- accept data ${buffer.toString()} ---`)
              buffers.push(buffer)
            })
            child.stdout.on('end', () => {
              let log = Buffer.concat(buffers)
              console.log(log.toString())
              console.log('Automated pull-out is completed')
            })
          }
          // json returned, configured in. / src/resModel
          res.end(resultString('success', 0))
        } else {
          // Other requests are not allowed to return
          return res.end(resultString('Not Allowed', 1))
        }
      } else {
        // github
        // Basically like the gitee above, there's one more step to verify identity
        console.log('--- Github platform ---')
        let signature = req.headers['x-hub-signature']
        // The sign method is configured in utils.js
        if (signature !== sign(body, SECRET)) {
          return res.end(resultString('Not Allowed', 1))
        }
        if (event === 'push') {
          console.log('--- push Mission hit ---')
          let payload = JSON.parse(body)
          console.log(payload.repository.name)
          let child = spawn('sh', [`./sh/${payload.repository.name}.sh`])
          let buffers = []
          child.stdout.on('data', buffer => {
            buffers.push(buffer)
          })
          child.stdout.on('end', () => {
            let log = Buffer.concat(buffers)
            console.log(log.toString())
            console.log('Automated pull-out is completed')
          })
        }
        res.end(resultString('success', 0))
      }
    })
  }
  res.end(resultString('Not Found', 1))
})

// Listener port, PORT is configured in config.js
server.listen(PORT, () => {
  console.log(`web-hook listen on http://localhost:${PORT}`)
})

Tips: Receives post parameters sent by github: Webhooks | GitHub Developer Guide

It is recommended to see the instructions of gitee platform (in Chinese, the parameters are similar) Gitee

2. Write sh file

./sh/*.sh

#!/bin/bash
WORK_PATH="/home/wwwroot/tools/vue-back"
echo "------ Enter the project catalogue ------"
cd $WORK_PATH
echo "------ Item catalogue in progress ------"
echo "------ Start cleaning code to prevent conflicts ------"
git reset --hard origin/master
git clean -f
echo "------ Clean up the code ------"
echo "------ Pull out master Branch code ------"
git pull origin master
echo "------ vue-back Continuous Integration Completed ------"
  1. Deploy to server
  • Deploy the written Node project to the server
  • Aliyun server needs to manually configure open custom port number
  • Node project recommends pm2

Automated Deployment Effect Map:

Keywords: Javascript github git JSON Vue

Added by cvsherri on Tue, 03 Sep 2019 12:44:25 +0300