0%

hexo自动构建部署从Travis CI迁移至GitHub Actions

很久没更新博客了,今天想更新一下发现构建失败,看了下是因为 Travis CI 开始商业化了,我的免费额度早就用完了,正好现在都在玩 GitHub Actions, 切换过来了. 使用的 Workflow 是基于 使用 GitHub Actions 自动部署 Hexo 博客 的, 感谢大大.

仓库和 Travis CI 时一样,master 为部署分支,source 分支为博客构建分支,blog 都在这里面。

Hexo 添加 Git 部署依赖

自动部署需要用到 hexo-deployer-git 依赖: npm install -save hexo-deployer-git.

编辑 hexo 配置:

1
2
3
4
5
6
deploy: 
type: git
repo: git@github.com:xweiba/xweiba.github.io.git
branch: master # 部署到的分支
name: xweiba
email: xiaoweiba1028@gmail.com

配置部署密钥

终端执行 ssh-keygen -t rsa -C "xiaoweiba1028@gmail.com" -f D:\github\xweiba\hexo-deploy-key, 即可生成 id_rsaid_rsa.pub 文件。

将公钥 hexo-deploy-key.pub 设置为仓库的部署密钥 Settings > Deploy keys:

然后在仓库的 Settings > Actions 中新增一个 secret,命名为 DEPLOY_KEY,把私钥 hexo-deploy-key 的内容复制进去,供后续使用。

编写 Workflow

Workflow 就是 GitHub Actions 的配置文件,类似于 .travis.yml

source 分支新建文件:

1
2
mkdir -p .github/workflows
touch .github/workflows/deploy.yml

编辑 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
62
name: Hexo Deploy

# 只监听 source 分支的改动
on:
push:
branches:
- source

# 自定义环境变量
env:
POST_ASSET_IMAGE_CDN: true

jobs:
build-and-deploy:
runs-on: ubuntu-latest

steps:
# 获取博客源码和主题
- name: Checkout
uses: actions/checkout@v2

# 这里用的是 Node.js 14.x
- name: Set up Node.js
uses: actions/setup-node@v1
with:
node-version: '14'

# 设置 yarn 缓存,npm 的话可以看 actions/cache@v2 的文档示例
- 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

# 从之前设置的 secret 获取部署私钥
- 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
git config --global user.name "xweiba"
git config --global user.email "xiaoweiba1028@gmail.com"
# 生成并部署
- name: Deploy
run: |
npx hexo clean && npx hexo d -g

部署

只要 source 分支有修改就会触发仓库 ActionsWorkflows 自动部署静态文件: