利用 GitHub Action 自动部署博客

利用 GitHub Action 自动部署博客

利用 Github Action 部署 Hugo 博客,以达到 写文章 -> git push -> 自动部署 -> 生效 的效果。

开始之前,建议先看看这篇文章:

利用 GitHub Action 实现 SSL 证书的自动续签

里面提到了一些 Github Action 的基础使用说明,一些简单的东西本文不再重复。

现在开始,从头开始部署我们的博客。

创建站点:

1
2
3
$ hugo new site blog
$ cd blog
$ git init

加载主题:

1
2
$ git submodule add some_theme_url themes/theme_name
$ cp -r themes/theme_name/exampleSite/* .

建议将主题作为博客的子模块引入。这一步省去了主题的相关配置过程,请自行查阅相关主题文档。配置好主题后,再继续之后的步骤。

新建文章:

1
$ hugo new posts/hello.md

添加 .gitignore 文件并创建一个 commit:

1
$ vim .gitignore

内容为:

1
2
3
.DS_Store

public/

然后提交。

1
2
$ git add .
$ git commit -m "init site"

在 Github 上创建名为 blog 的私有仓库,创建一个 PERSONAL_TOKEN 并添加到该仓库的 Secrets 中。

关于创建 Personal access token:点击这里,填入 token name,如 Github Workflows。scpoes 的话,只需要选择 repo 即可。点击 Generate token,然后记下页面上显示的 token,并作为 PERSONAL_TOKEN 填入仓库的 Secrets 中。

然后将本地站点文件推送到远端。

1
2
$ git remote add origin [email protected]:Your_name/blog.git
$ git push --set-upstream origin main

创建名为 your_github_name.github.io 的公共仓库。

在 blog 仓库里创建 Github Action。来一份配置文件:

 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: CI

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          token: ${{ secrets.PERSONAL_TOKEN }}
          submodules: true
          fetch-depth: 0
      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: 'latest'
      - name: Build
        run: hugo --minify
      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          personal_token: ${{ secrets.PERSONAL_TOKEN }}
          external_repository: Your_Github_Name/your_github_name.github.io
          publish_branch: gh-pages
          publish_dir: ./public
          force_orphan: true
          allow_empty_commit: true
          cname: blog.example.com
          user_name: 'github-actions[bot]'
          user_email: 'github-actions[bot]@users.noreply.github.com'
          full_commit_message: ${{ github.event.head_commit.message }}

简单说下配置中的几个步骤:

  1. checkout 站点文件。这里配置了 submodules: true,会同时检出作为子模块的博客主题。如果你没有将博客主题作为站点子模块的话,还要写一个 checkout 主题的步骤。

  2. 安装 Hugo。

  3. 构建站点静态文件。

  4. 部署站点静态文件。这部分说的是:

    将 public 目录下的文件部署到 your_github_name.github.io 仓库的 gh-pages 分支上;同时生成内容为 blog.example.comCNAME 文件;即使 blog 仓库进行了空提交,也要执行部署任务;每次部署都清空 your_github_name.github.io 仓库之前的部署记录(commit 记录)。

填写 Action 文件的文件名,点击 Start commit,输入 commit message 与 user email (可选),点击 Commit new file。

现在站点正在自动构建,构建过程可以在 Action 页查看。构建完成后,即可打开 https://blog.example.com 查看效果。

以上。


利用 GitHub Action 自动部署博客

https://blog.imaple.net/posts/auto_hugo/

作者

iMaple

发布于

2020-09-11

更新于

2020-09-11

许可协议

CC BY-NC 4.0

评论