github action 是什么

github actions 由一项或多项作业组成,可以计划或由事件触发。 工作流程可用于在 GitHub 上构建、测试、打包、发布或部署项目。

使用 github action 自动部署博客

我使用的hugo+nginx的博客方案,原本的基本流程为

  1. 在本地编辑文稿

  2. 使用hugo命令进行编译,生成一个public文件夹

  3. 将public文件夹打包压缩

  4. scp到服务器上,解压发布

现在我们使用github action的流程为

  1. 在本地编辑文稿

  2. push到github仓库

  3. github action自动帮我们编译生成public文件夹,并发送到服务器


下面进行github action实战

  1. 创建仓库、初始化项目…

  2. 进入仓库,点击Actions进行编辑 图示

  3. 自定义action流程 图示

  1. 下面贴一下我部署博客的yaml
# This is a basic workflow to help you get started with Actions

name: CI

# Controls when the action will run.
on:
  # Triggers the workflow on push or pull request events but only for the master branch
  push:
    branches: [ master ]
  #   pull_request:
  #     branches: [ master ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # 从master上获取最新代码
      - name: Checkout Github Action
        uses: actions/checkout@master

      #- name: Hugo Actions
      # You may pin to the exact commit or the version.
      # uses: srt32/hugo-action@45dd72ab904158d21657b29c5aa67007a8fcdaba
      - name: hugo-build
        uses: srt32/hugo-action@v0.0.3

      - name: SCP Command to Transfer Files
        # You may pin to the exact commit or the version.
        # uses: appleboy/scp-action@edc8ec9139a2687bcebf0249d0352ff2a988df00
        uses: appleboy/scp-action@v0.1.1
        with:
          # scp remote host
          host: ${{ secrets.VM_IP }}
          # scp remote port
          port: 22
          # scp username
          username: ${{ secrets.VM_USER }}
          # scp password
          password: ${{ secrets.VM_PASSWORD }}
          # target path on the server
          target: /usr/share/nginx/html
          # scp file list
          source: public/*
          # remove target folder before upload data
          #           rm: true
          # enable debug message
          debug: true
          # remove the specified number of leading path elements
          strip_components: 1
          # use `--overwrite` flag with tar
          overwrite: true
          # temporary path for tar file on the dest host
          tar_tmp_path: /tmp

注意修改一下steps中scp的逻辑,包括target文件夹路径等等

服务器的ip、账号、密码强烈推荐使用github的Secrets(在仓库Settings中设置)保障安全


参考资料