iami233
iami233
文章152
标签38
分类4

文章分类

文章归档

Github Actions 自动化部署 Hexo

Github Actions 自动化部署 Hexo

上一次使用 Gtihub Actions 还是用在 TenAPI Docs 项目,通过 Actions 自动化编译 VuePress,不过目前每次更新文章到也不是很麻烦,直接两条命令完事。

1
2
hexo n 'title' # 新建文章
hexo g -d # 编译部署

但是目前的痛点就是:每次终端和 Github 通信都需要开一下代理,而不像浏览器设置了分流规则… 其次就是面临备份的问题,所以干脆全套迁移线上了。

创建仓库

这里我们需要创建两个仓库

  • Blog - 私有仓库,用来存储你博客文件
  • [username].github.o - 公有仓库,用来存储编译后的博客文件及 Github Pages

生成公私钥

使用 CMD 执行以下命令,会在当前目录生成公私钥:hexo-action.pubhexo-action

1
ssh-keygen -t rsa -b 4096 -C "$(git config user.email)" -f hexo-ation -N ""

配置Deploy Key

<username>.github.ioSettings -> Deploy keys -> Add deploy key 中添加公钥 hexo-action.pubAllow write access 勾选,地址如下

1
https://github.com/<usernmae>/<repo>.github.io/settings/keys

BlogSettings -> Secrets -> Secrets and variables -> actions -> New repository secret 中添加私钥 hexo-action,同时命名为 ACTIONS_DEPLOY_KEY。具体地址如下

1
https://github.com/<usernmae>/<repo>/settings/secrets/actions

配置Github Actions

这里主要用的 actions-gh-pages 作为 Actions ,大家唯一需要修改的地方为部署仓库: external_repository 和提交分支:publish_branch 配置项。同时当 Blog 仓库的 main 分支(配置项:branches)发生 pull 时候将自动触发 Actions,将以下内容存放到 .github/workflows/deployment.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
name: Hexo-Build-Pages

on:
push:
branches:
- main

jobs:
pages:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v3
with:
submodules: true
- name: Use Node.js 16.x
uses: actions/setup-node@v2
with:
node-version: '16.18.1'
- name: Cache NPM dependencies
uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.OS }}-npm-cache
restore-keys: |
${{ runner.OS }}-npm-cache
- name: Install Dependencies
run: npm install
- name: Build
run: npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
external_repository: <username>/<usernmae>.github.io
publish_dir: ./public
publish_branch: master
user_name: 'github-actions[bot]'
user_email: 'github-actions[bot]@users.noreply.github.com'

目录总览

最终 Blog 仓库目录结构大致如下

1
2
3
4
5
6
7
8
9
10
Blog
├─ .github
│ └─ workflows
│ └─ deployment.yml
├─ .gitignore
├─ _config.yml
├─ db.json
├─ package.json
├─ source
└─ themes
本文作者:iami233
本文链接:https://5ime.cn/hexo_auto_deploy.html
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可