Github Actions CI/CD

Github Actions 是 Github 提供的一套 CI/CD 解决方案,允许开发者创建能自动构建、测试、发布和部署代码的工作流程。本文主要介绍如何使用 Github Actions 持续集成前端应用(演示项目代码地址在会在文末给出)。

配置workflow

Actions->选择新建Node.js的工作流

BW35XF.png

.github/workflows/node.js.yml

# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: Node.js CI

# on 何时触发 jobs ,默认是 push 和 pull master 分支时
on:
  push:
    branches: [master]
  # pull_request:
  #   branches: [master]

jobs:
  build:
    # job 的运行环境
    # runs-on: ubuntu-latest
    runs-on: self-hosted

    # 测试在不同 Node 版本中运行项目
    strategy:
      matrix:
        # node-version: [10.x, 12.x, 14.x]
        node-version: [14.x]

    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
          registry-url: 'https://registry.npmjs.org'
      # - run: npm ci
      # 安装需要的依赖
      - run: npm i
      # --if-present 如果命令存在则执行,定义在 package.json 的 script 中
      - run: npm run build --if-present
      # - run: npm test
  • on

    何时触发 jobs ,默认是提交和拉取 master 分支时

  • jobs

    • runs-on

      配置 jobs 的运行环境,默认是运行在 Github 提供的 ubuntu 系统上,可改为self-hosted运行在自己的 vps 上

    • strategy

      测试在不同 Node 版本中运行项目

  • steps

    每个 job 需要执行的步骤

    • uses

      执行的 Action ,每个 Action 可以看做是实现特定功能独立的脚本,比如actions/checkout@v2是官方提供的拉取仓库分支代码的 Action。更多Actions可在 Marketplace中查找

    • run

      运行命令

Runner

Runner的作用是执行脚本,如果使用sefl-hosted的部署方式,需要在服务器上安装GitHub Actions Runner

runner安装

项目目录->Settings->Actions->Add self-hosted runner

  • 下载

BWNZwD.png

  • 配置

BWapx1.png

# 输入 runner 的名字
Enter the name of runner: [press Enter for VM-0-9-ubuntu] vue-shop-admin
# 输入 附加label
Enter any additional labels (ex. label-1,label-2): [press Enter to skip] 
# 输入工作目录
Enter name of work folder: [press Enter for _work]
  • 运行
./run.sh

查看运行过程

Actions->build

BWwuHf.png

直接运行./run.sh会在窗口关闭时结束runner进程,接下来解决这个问题

runner命令
  • 查看可用的runner命令
sudo ./svc.sh
  • 将runner注册为服务

    注册为服务后可以在后台和开机后自动运行runner

sudo ./svc.sh install
  • 查看runner状态
sudo ./svc.sh status
  • 运行runner
sudo ./svc.sh start

遇到的问题

  1. 运行runner
./run.sh

A session for this runner already exists.

解决方案

删除刚才运行的Runner,同时删除actions-runner文件夹,重新执行Runner下载、配置和运行

BWxsKg.png

删除runner
./config.sh remove --token AG42HFBCRKCL7OLBXKTERES7UTLBA

如果遇到

Removing service
Failed: Removing service
Unconfigure service first

先卸载服务

sudo ./svc.sh uninstall

重新执行删除命令

./config.sh remove --token AG42HFBCRKCL7OLBXKTERES7UTLBA
使用nginx托管站点

安装过程参考https://www.jianshu.com/p/0abe6d29daa7

配置过程参考https://www.jianshu.com/p/59b94ed30740

你可能感兴趣的:(Github Actions CI/CD)