使用GitHub Actions部署Hexo博客

这两天注意到 GitHub 上的 Actions 功能就详细了解了一下,没想到这功能已经出来四五年了。学习了一下,发现用来部署博客很合适,只要维护博客源文件就好,每次发布新文章到备份仓库,GitHub 自动部署静态文件,太完美了。即便是以后换了电脑,也能省去搭建本地环境的麻烦了。个人用户的免费计划已经足够使用了。

流程

看了网上一些资料,很多没有将清楚流程和准备工作,直接上 Actions 代码,看的人很疑惑。

整个流程需要两个仓库:一个私有仓库用来存储源文件,一个公有仓库用来部署静态文件。在源文件仓库添加 Actions 工作流,每次 push 到源文件仓库时,Actions 自动触发部署,然后将生成的静态文件 push 到公有静态文件仓库。

当然一个仓库应该也可以,从 A 分支的源文件生成静态文件部署到 B 分支。

步骤如下:

  1. 新建源文件私有仓库,新建公有的静态文件部署仓库
  2. 在源文件仓库的 Secrets and variables > Actions 下新增一个 “Repository secret”,这个 secret 在 Actions 中会用到
  3. 在源文件仓库新建 Actions,代码见下方,其中的 secrets 即为上一步中生成的 sercet
  4. 完成

workflows

感谢 yifangzheng 的 Actions 脚本,这个脚本还支持推送 gitee 和 coding。

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
62
63
name: Hexo blog auto deploy

# 触发条件:在 push 到源文件仓库分支后触发
on:
push:
branches:
- main

env:
TZ: Asia/Shanghai

jobs:
blog-cicd:
name: Hexo blog build & deploy
runs-on: ubuntu-latest # 使用最新的 Ubuntu 系统作为编译部署的环境

steps:
- name: Checkout codes
uses: actions/checkout@v4

- name: Setup node
# 设置 node.js 环境
uses: actions/setup-node@v1
with:
node-version: '18.x'

- name: Cache node modules
# 设置包缓存目录,避免每次下载
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}

- name: Install hexo dependencies
# 下载 hexo-cli 脚手架及相关安装包
run: |
npm install -g hexo-cli
npm install

- name: Generate files
# 编译 markdown 文件
run: |
hexo clean
hexo generate

- name: Deploy hexo blog
env:
# Github 仓库
GITHUB_REPO: github.com/lozhu20/lozhu20.github.io
# Coding 仓库
# CODING_REPO: e.coding.net/yifanzheng/blogs.git
# Gitee 仓库
# GITEE_REPO: gitee.com/yifanzheng/yifangzheng.gitee.io.git
# 将编译后的博客文件推送到指定仓库
run: |
cd ./public && git init && git add .
git config user.name "lozhu20"
git config user.email "zhulongkun20@icloud.com"
git add .
git commit -m "GitHub Actions Auto Builder at $(date +'%Y-%m-%d %H:%M:%S')"
git push --force "https://${{ secrets.HEXO_BLOG_DEPLOY_KEY }}@$GITHUB_REPO" master:main
# git push --force "https://RoYFbFDSfM:${{ secrets.CODING_TOKEN }}@$CODING_REPO" master:master
# git push --force "https://yifanzheng:${{ secrets.GITEE_ACCESS_TOKEN }}@$GITEE_REPO" master:master

问题记录

报错1

执行到 Deploy hexo blog 报错,日志:

1
2
3
error: src refspec main does not match any
error: failed to push some refs to 'https://github.com/lozhu20/lozhu20.github.io'
Error: Process completed with exit code 1.

这是因为静态仓库分支不存在导致的,检查 git push 的分支名是否正确:

1
git push --force "https://${{ secrets.HEXO_BLOG_DEPLOY_KEY }}@$GITHUB_REPO" master:main

冒号前是 master 固定的,冒号后是静态文件仓库的分支名。

报错2

Actions 顺利执结结束,静态文件成功推送,但是打开网站首页空白且无报错。仔细查看了日志,发现 Generate files 步骤有告警:

1
2
3
4
WARN  No layout: about/index.html
WARN No layout: categories/index.html
WARN No layout: friends/index.html
...

再往前检查,发现推送到源文件仓库的文件中 themes 目录下的两个主题文件夹都没有推送上去。修复了这个问题重新推送,再次触发工作流后就能正常访问了。