使用 Github Actions自动部署Hexo

话说每次写文章都需要执行 hexo g -d,如果换个机器想记录点东西还得备一套nodejs 环境,着实麻烦,最近发现Github Actions 非常好用,只需要写完文章,将markdown文件丢到GitHub 去就可以自动触发编译,整个过程非常的快,下面将介绍如何去使用

准备2个仓库

首先需要准备2个仓库,

  • 一个是你博客托管在GitHub的公共仓库用来提供博客的访问服务
  • 一个是私有仓库用来上传hexo源码

比如我的公共仓库就是 awen.github.io 而私有仓库你自己取名字,我这里叫 deploy_blog,然后把本地的hexo 环境中的文件全部上传到私有仓库去

创建私钥

1
ssh-keygen -t rsa -b 4096 -f ~/.ssh/github-actions-deploy

在Settings->SSH and GPG keys添加刚刚生成的公钥,名称随意。

在私有仓库的Settings->Secrets里添加刚刚生成的私钥,名称为 ACTION_DEPLOY_KEY。

配置hexo 的 config.yml

在hexo 的站点配置文件下的deploy 中配置repo 为你博客公共仓库的git地址

1
2
3
4
deploy:
- type: git
repo: [email protected]:monkey-wenjun/awen.github.io.git
branch: master

配置 workflows

在私有仓库的Actions选项卡下点击新建workflow,编写如下配置。

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
name: Deploy Blog

on: [push] # 当有新push时运行

jobs:
build: # 一项叫做build的任务

runs-on: ubuntu-latest # 在最新版的Ubuntu系统下运行

steps:
- name: Checkout # 将仓库内master分支的内容下载到工作目录
uses: actions/checkout@v1 # 脚本来自 https://github.com/actions/checkout

- name: Use Node.js 12.x # 配置Node环境
uses: actions/setup-node@v1 # 配置脚本来自 https://github.com/actions/setup-node
with:
node-version: "12.x"

- name: Setup Hexo env
env:
ACTION_DEPLOY_KEY: ${{ secrets.ACTION_DEPLOY_KEY }}
run: |
# set up private key for deploy
mkdir -p ~/.ssh/
echo "$ACTION_DEPLOY_KEY" | tr -d '\r' > ~/.ssh/id_rsa # 配置秘钥
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
# set git infomation
git config --global user.name 'monkey-wenjun' # 换成你自己名字
git config --global user.email 'xxxxx' # 换成你的邮箱
# install dependencies
npm i -g hexo-cli # 安装hexo
npm i

- name: Deploy
run: |
# publish
hexo generate && hexo deploy # 执行部署程序

你也可以在本地的.github 目录下新建一个workflows 目录,在里面新建一个yml 文件内容如上,然后将文件push 到github 上去就会自动触发编译了。

编译过程中如果有错误,在GitHub的actions 中可以看到一个叉,发布成功的是一个绿色的勾

发布失败的可以点进去看下是哪一个步骤出错了,然后对应的修改即可,比如我这里是deploy 这步错了

点击展开,可以看到,根据报错调整你的workflows 文件即可