使用GitHub Action自动部署博客

目标

把 blog 源码放在一个仓库,之后只要 push 内容到该仓库,就用 GitHub action 自动构建博客,并把 public 目录下的内容推送到 user.github.io 仓库

开始

Workflow

首先,在 GitHub 创建一个名为 blog 的仓库,用来放博客源码。当然也可以是其他名字。


然后,在 blog 仓库下创建 .github/workflows/gh-pages.yml 文件。添加以下内容:

Hugo
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
name: GitHub Pages

on:
push:
branches:
- main # Set a branch to deploy
pull_request:

jobs:
deploy:
runs-on: ubuntu-20.04
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
steps:
- uses: actions/checkout@v3
with:
submodules: true # Fetch Hugo themes (true OR recursive)
fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod

- name: Setup Hugo
uses: peaceiris/actions-hugo@v2
with:
hugo-version: '0.101.0'
extended: true

- name: Build
run: hugo --minify

- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
external_repository: XXiaoA/XXiaoA.github.io
publish_branch: main
publish_dir: ./public
commit_message: ${{ github.event.head_commit.message }}


此外,记得把 external_repository 改为自己仓库的名字

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

on:
push:
branches:
- main
pull_request:

jobs:
build:
runs-on: ubuntu-latest
name: A job to deploy blog.
steps:
- name: Checkout
uses: actions/checkout@v1
with:
submodules: true # Checkout private submodules(themes or something else).

# Caching dependencies to speed up workflows. (GitHub will remove any cache entries that have not been accessed in over 7 days.)
- name: Cache node modules
uses: actions/cache@v1
id: cache
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: npm ci

# Deploy hexo blog website.
- name: Deploy
id: deploy
uses: sma11black/hexo-action@v1.0.3
with:
deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
user_name: your github username # (or delete this input setting to use bot account)
user_email: your github useremail # (or delete this input setting to use bot account)
commit_msg: ${{ github.event.head_commit.message }} # (or delete this input setting to use hexo default settings)
# Use the output from the `deploy` step(use for test action)
- name: Get the output
run: |
echo "${{ steps.deploy.outputs.notify }}"

Token

在终端运行以下命令

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


不出意外,会有两个文件生成:

  • gh-pages.pub 公钥
  • gh-pages 私钥


接着打开 GitHub 的 blog 仓库,点击 Settings -> Secrets -> Actions 添加你的私钥(也就是 gh-pages 文件的内容),命名为 ACTIONS_DEPLOY_KEY


然后点开 user.github.io 仓库。进入设置点击 Deploy key 把你的公钥添加进去。记得点击 Allow write access 选项。


然后就大功告成了!🥳

References


使用GitHub Action自动部署博客
https://xxiaoa.github.io/posts/2dd3bdb5/
Author
XXiaoA
Posted on
July 2, 2022
Licensed under