背景

为了方便可以使用 GitHub Actions 实现博客自动发布,将静态博客页面部署到多个服务器上,比如 GitHub Pages,Gitee pages 以及云服务器上。本文介绍使用 GitHub Actions 实现将 Hexo 博客自动编译并发布到 GitHub Pages 上。

流程

SSH 秘钥

生成秘钥用于仓库间的推送:

1
ssh-keygen -f hexo-deploy-key -t rsa -C "2284672469@qq.com"

以上命令会在当前路径下生成:秘钥 hexo-deploy-key 和公钥 hexo-deploy-key.pub,然后分别添加到对应的文件中。

  • 页面文件仓库(即 dreamhomes.github.io): 在 Settings > Deploy keys 中添加 Deploy key,内容为 hexo-deploy-key.pub 文件内容,同时勾选 Allow write access 选项。
  • 博客源文件库:在 Settings > Secrets 中添加一个 Secret,名称为 DEPLOY_KEY,内容为 hexo-deploy-key 文件内容。后续在 Workflow 中通过名称 DEPLOY_KEY 使用这个密钥。

Workflow 配置

在博客源文件库中新建文件 .github/workflows/deploy.yml,配置内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# This is a basic workflow to help you get started with Actions

name: Blog deploy

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

# 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-and-deploy:
# 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:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2

# Runs a set of commands using the runners shell
- name: Set Node.js
uses: actions/setup-node@v1
with:
node-version: '12'

# Cache node modules to accelerate
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"

- name: Use yarn cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-

- name: Install dependencies
run: yarn install --prefer-offline --frozen-lockfile

- name: Set up environment
env:
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
run: |
sudo timedatectl set-timezone "Asia/Shanghai"
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts

- name: Deploy
run: |
npx hexo clean && npx hexo generate && gulp && npx hexo deploy

最后修改 Hexo 源文件夹下的 _config.yml 文件指定 git 配置即可:

1
2
3
4
5
6
7
deploy:
- type: git
repo: git@github.com:dreamhomes/dreamhomes.github.io
# repo: https://gitee.com/dreamhomes/dreamhomes.git
branch: master
name: dreamhomes
email: 2284672469@qq.com

效果

一次部署大概需 2min 左右,比本地稍慢。

CI/CD