Hugo+Github Pages快速搭建个人博客三:Github Actions自动部署

前言

通过之前的文章,我们已经把博客站点部署完成,并且添加了giscus评论系统,但是每次发布文章都需要手动执行hugo命令生成站点静态文件,并把文件推送到仓库当中等待部署才能发布。为了简化我们的发布流程,本文将介绍使用Github Actions 来自动构建hugo静态文件,并推送至启用github pages的仓库当中。

1. 创建站点文章仓库

在第一篇中我们只在github上创建了waouooo.github.io仓库,用于保存站点的静态文件,并开启Github Pages。但是我们在使用hugo new site waouooo创建站点文件夹时也对站点文件夹做了git init 操作,因此我们也可以将站点的内容保存至github中。点此创建

2. 关联远程仓库至本地hugo 站点元数据git仓库,并推送

仓库创建完成之后github页面会展示以下内容: 因为我们本地已经有仓库,只需要执行以下内容即可:

git remote add origin git@github.com:waouooo/myblog.git
git push -u origin master

3. 生成sshkey 用于Github Actions推送hugo生成的静态文件至托管仓库

-C 参数指定github用户的邮箱

ssh-keygen -t rsa -C waouooo@163.com
# 以下内容为输出
Generating public/private rsa key pair.
# 此处输入保存新ssh key的文件路径,不要回车,否则使用默认文件名,会被覆盖。其他地方可一路回车
Enter file in which to save the key (/Users/waouooo/.ssh/id_rsa): id_rsa_deploy_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa_deploy_key
Your public key has been saved in id_rsa_deploy_key.pub
The key fingerprint is:
SHA256:iKKuSQt+jFiZc3UbeSDY………………tYrvgO+FRI7tSE waouooo@163.com
The key's randomart image is:
+---[RSA 3072]----+
|     o           |
|    . o .        |
|     + . oE o    |
|    o.o.= .= o   |
|  .+.o. S=+.o.   |
| .=.o . . =o+..  |
|+o o     o O.  . |
|*o.o      +.+ .  |
|++.       .oo+   |
+----[SHA256]-----+

以上执行完成之后会在当前目录生成 id_rsa_deploy_key, id_rsa_deploy_key.pub两个文件

4. 将生成的公钥: id_rsa_deploy_key.pub 保存至需要部署的waouooo.github.io项目中

5. 使用ssh私钥: id_rsa_deploy_key 在站点元数据仓库中创建secret

Name建议使用DEPLOY_KEY, 需要下文Github Actions 的Workflow配置文件中使用

6. 创建Github Actions 的工作流(workflow)

将以下内容填充至配置中:

name: GitHub Pages

on:
  push:
    branches:
      - master  # Set a branch to deploy

jobs:
  deploy:
    runs-on: ubuntu-22.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: 'latest'
          extended: true

      - name: Build
        run: hugo --minify

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        if: ${{ github.ref == 'refs/heads/master' }}
        with:
         deploy_key: ${{ secrets.DEPLOY_KEY }}  # 上文保存至本仓库secrets中的ssh秘钥变量名
         external_repository: waouooo/waouooo.github.io # 需要将静态文件推送的仓库名
         publish_branch: main # 对应目的仓库的目的分支,因为waouooo主分支为main
         publish_dir: ./public # 推送的文件夹,hugo --minify命令会将静态文件生成至./public文件夹中
         commit_message: ${{ github.event.head_commit.message }} # 指定commit信息

完成后点击start commit完成配置

注意:此时仓库中提交了一个.github/workflows/main.yml的新文件,需要使用git pull 同步至本仓库先,方式下次推送时发生冲突

总结

至此自动化推送已经实现,之后只需要添加文章之后将其推送到远端仓库即可自动触发Github Actions执行自动编译并推送至站点仓库waouooo.github.io中

参考链接

Hugo setup

actions-gh-pages