通过GitHub Actions自动化部署Hexo博客

by CUNOE, April 2, 2023

Github Actions 是 Github 推出的一项 CI/CD 服务,可以通过简单的配置文件,实现自动化部署。本文将介绍如何转移原本的Blog到 Github Actions 自动化部署 Hexo 博客,根据本文的配置,每次提交代码到 Github 仓库,Github Actions 就会自动构建并部署博客。

开始

创建私有仓库 EXAMPLE-BLOG

在 Github 上创建一个私有仓库,用于存放博客的源代码,这里命名为 EXAMPLE-BLOG

创建公开仓库 EXAMPLE.github.io

在 Github 上创建一个公开仓库,用于存放博客的静态文件,这里命名为 EXAMPLE.github.io

配置Deploy Key

生成公私钥

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

此时会在当前目录下生成两个文件:gh-pagesgh-pages.pub,分别为私钥和公钥。

添加Deploy Key

EXAMPLE.github.ioSettings -> Deploy keys -> Add deploy key 中添加公钥 gh-pages.pubAllow write access 勾选。

EXAMPLE-BLOGSettings -> Secrets -> New repository secret 中添加私钥 gh-pages,命名为 ACTIONS_DEPLOY_KEY

配置 Github Actions

此处会使用到第三方的Actions:peaceiris/actions-gh-pages

同时因为我的博客使用了主题,这里采用submodules的方式引入主题,所以需要在checkout时加上submodules: true

name: 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: EXAMPLE/EXAMPLE.github.io
          publish_dir: ./public
          user_name: 'github-actions[bot]'
          user_email: 'github-actions[bot]@users.noreply.github.com'

上传博客源代码并测试

将博客源代码上传到 EXAMPLE-BLOG,并提交一次代码,Github Actions 就会自动构建并部署博客。

第一次部署时,由于 EXAMPLE.github.io 仓库为空,有可能会出现错误,此时需要在 Settings -> Options -> GitHub Pages 中选择 gh-pages 分支,然后再次提交代码。

结束

通过这次部署以后,每次提交代码到 Github 仓库,Github Actions 就会自动构建并部署博客,不需要再手动部署了,也是美滋滋。以后不需要Hexo的环境也可以写博客了,或许会让我写博客的频率更高一些吧~