使用 GitHub Actions 自动部署 hexo

写在前面

好朋友林桑推荐(不是鬼子),他说使用 GitHub Actions 可以白嫖 GitHub 的服务器资源来给 hexo 生成静态文件,然后我就开始研究咋整…

林桑的文章:使用 Github Actions 来自动化部署 hexo 博客

GitHub Actions

个人感觉,GitHub Actions 就是一个自动化的工具,设置脚本,它帮你一步一步执行,脚本的具体实现,具体在 .github\workflows\whatever-name.yml 文件。(whatever-name:随便啥名…)

image-20220413143939941

具体去看官方文档:GitHub Actions

理解

而用 Actions 来自动部署 hexo,就需要理解整个过程…

我们在本地给 hexo 生成静态文件并 deploy 的命令是:

1
2
3
hexo clean
# hexo generate
hexo deploy

而我们要自动部署,就需要新建私有库(最好),把源码推到远程库,GitHub Actions 感应到 push,就会帮我们执行这些命令,生成静态文件,deploygithub.io 库中。

这些命令又需要相对应的环境,所以要在之前先安装相关运行环境,如 nodejshexo-cli 等。

GitHub 明白我们的指令,就需要上面提到的“脚本文件”:

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 随便起
name: deploy
# 在 master 分支 push 的时候激活 Actions
on:
push:
branches:
- master
jobs:
# 可以有多个 job
# deploy 为一个 job 的名字,可以随意的取
deploy:
# 运行在最新的 ubuntu 容器中
runs-on: ubuntu-latest
steps:
# 定义这个任务的步骤
- name: checkout repo
# 使用封装好的一些 actions
# 这里的 actions/checkout@v3 的作用为拉取代码到工作区
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v1
with:
node-version: '14.15.0'
- name: Setup Hexo
env:
HEXO_DEPLOY_KEY: ${{ secrets.HEXO_DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh/
echo "$HEXO_DEPLOY_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.email "kebabshell@163.com"
git config --global user.name "KebabShell"
npm install hexo-cli -g
npm install
- name: Deploy
run: |
hexo clean
hexo deploy

密钥

理解了上面的整个过程,那么就会想到,在 GitHub 自己的环境下,怎么有权限推内容到我们的库呢?

在本地,我们推内容到远程仓库是需要 ssh 验证的,所以要在 GitHub 的环境下 push 内容,GitHub 环境就需要我们自己的密钥!

而密钥又不能直接写在 yml 中,这时候就需要 GitHub 仓库中的 Actions secrets 了!

image-20220413145439062

就像 yml 提到的:

1
2
3
4
5
6
7
8
9
10
11
- name: Setup Hexo
env:
# HEXO_DEPLOY_KEY 就是自定义的 key,把密钥写入 id_rsa 与远程库进行 ssh 验证
HEXO_DEPLOY_KEY: ${{ secrets.HEXO_DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh/
echo "$HEXO_DEPLOY_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.email "kebabshell@163.com"
git config --global user.name "KebabShell"

效果

当你把更改 push 到私有库 master 分支,就会触发 Actions,你可以在 Actions 页看到:

image-20220413151351878

你还能点进去看具体的执行过程:

image-20220413151619289

最后

完成上述工作,以后写博文就只需要提交更改,生成静态文件和发布的任务就交给 GitHub

白嫖党永不为奴