2022-10-08    2022-10-08    647 字  2 分钟

记录一下如何使用 Github Actions 部署 Hugo 站点

创建代码仓库

这个时候需要两个代码仓库

  • 一个用来存放 hugo 源文件(可以是私密的也可是是公开的,名称为 blog)
  • 一个用来存放静态网站(名称为 yourname.github.io,公开的)

配置 Workflow

在 blog 仓库下创建=.github/workflows/hugo.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
name: github pages

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  deploy:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v2
        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: 'latest'
          # extended: true

      - name: Build
        run: hugo --minify

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        if: github.ref == 'refs/heads/main'
        with:
          deploy_key: ${{ secrets.DEPLOY_TOKEN }} # 和你在仓库中填写的表单名一致
          external_repository: shanyouli/shanyouli.github.io
          # publish_branch: hugo
          publish_dir: ./public
          keep_files: false
          publish_branch: main # web 代码库的默认分支
          # 如果使用自定义域名,还需要添加下面一行配置
          # cname: www.fournoas.com

该配置使用了两个第三方的 Actions ,分别是hugo setupgithub pages action,前者用于安装 Hugo ,后者用于部署静态站点

配置 SSH Key

Github Page action 支持三种方式验证身份

  • depoly key
  • github token
  • personal token

我使用的是 depoly key

创建一个 ssh key

1
2
3
4
ssh-key -t rsa -b 4096 -C "$(git config user.email)" -f gh-pages -N ""
# you will get 2 files:
#   gh-pages.pub (public key)
#   gh-pages (private key)

在 <yourName>.github.io 仓中设置公钥

访问如下地址设置 Public key

1
2
https://github.com/<YourName>/<yourName>.github.io/settings/keys/new
# YourName 为你的帐号名

表单中的 Title 随意填写,将刚才生成的 gh-pages.pub 文件内容填入 Key 中,勾选 Allow write access ,点击 Add key 按钮保存。

在 blog 仓中设置 Private key

设置私钥的地址如下

1
https://github.com/<YourName>/blog/settings/secrets/actions/new

表单中的 Name 填入 DEPLOY_TOKEN ,将刚才生成的 gh-pages 文件内容填入 Value 中,点击 Add secret 按钮保存。

执行 GitHub Actions

将 blog 仓库的代码提交并推送到 GitHub ,会自动触发 GitHub Actions 执行。可以访问如下网址来查看 Workflows 是否执行成功:

1
https://github.com/<YourName>/blog/actions