GitHub Actions 自动部署 Hexo 博客

Hexo 官方文档的 GitHub Pages 部署方案[1]需要注册第三方账号且绑定信用卡,所以创建博客时选择了一键部署[2]的方案,但是需要手动使用 hexo clean && hexo d 部署博客,有些麻烦,于是决定改为 GitHub Actions 自动部署。

准备工作

分别设置博客仓库和部署仓库,部署仓库为 GitHub Pages

配置 SSH

在本地生成一对 SSH 密钥,注意更改文件名避免将正在使用的密钥覆盖。

1
ssh-keygen -t ed25519 -C "your_email@example.com"

博客仓库Settings -> Secrets -> Actions 中添加 SSH 私钥,命名为 SSH_DEPLOY_KEY

添加私钥

部署仓库Settings -> Deploy keys 中添加 SSH 公钥,注意勾选 Allow write access

添加公钥

勾选 Allow write access

配置 hexo-deployer-git

安装 hexo-deployer-git

1
npm install hexo-deployer-git

然后在 _config.yml 中添加以下内容[2]

1
2
3
deploy:
type: 'git'
repo: git@github.com:Username/Repository

编写 Workflow

创建 .github/workflows/deployment.yml,写入以下内容,注意修改仓库地址和 Git 配置。此时当 push 到博客仓库时,GitHub Actions 将会自动部署。

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
name: Deployment
on: push

jobs:
deployment:
runs-on: ubuntu-latest
name: Deployment

steps:
- name: Check Out
uses: actions/checkout@v3

- name: Clone Repo
uses: actions/checkout@v3
with:
repository: Username/Repository
path: .deploy_git

- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16

- name: Setup Git
run: |
git config --global user.name "Example"
git config --global user.email "email@example.com"

- name: Setup SSH Key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_DEPLOY_KEY }}" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519

- name: Deploy
run: |
npm install --location=global hexo-cli
npm install
hexo d

Workflow 解析

两个 Checkout 的作用是切换到博客仓库最新提交,并且将部署仓库克隆到 .deploy_git,也就是 Hexo 的部署目录。

1
2
3
4
5
6
7
8
- name: Check Out
uses: actions/checkout@v3

- name: Clone Repo
uses: actions/checkout@v3
with:
repository: Username/Repository
path: .deploy_git

下一步安装 Node,版本需要与博客使用的版本相同。

1
2
3
4
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16

设置提交的用户名和邮箱。

1
2
3
4
- name: Setup Git
run: |
git config --global user.name "Example"
git config --global user.email "email@example.com"

将存储在仓库 Secrets 的 SSH 私钥存储到本地供 Git 使用。mkdir 是为了下一步可以在 ~/.ssh 目录中创建文件,chmod 设置权限,Git 才能使用私钥[3]

1
2
3
4
5
- name: Setup SSH Key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_DEPLOY_KEY }}" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519

最后安装 Hexo 和依赖,运行 hexo d 部署博客。

1
2
3
4
5
- name: Deploy
run: |
npm install --location=global hexo-cli
npm install
hexo d

参考文献

  1. 将 Hexo 部署到 GitHub Pages. Hexo. 2022-06-11 [2022-06-17]. (原始内容存档于2022-06-17).
  2. 部署. Hexo. 2022-06-11 [2022-06-17]. (原始内容存档于2022-06-17).
  3. 利用 Github Actions 自动部署 Hexo 博客. Sanonz. 2020-05-12 [2022-06-17]. (原始内容存档于2021-06-18).

GitHub Actions 自动部署 Hexo 博客
https://blog.zhanganzhi.com/zh-CN/2022/06/0800d76d306e/
作者
Andy Zhang
发布于
2022年6月17日
许可协议