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
生成公私钥
1ssh-keygen -t rsa -b 4096 -C "$(git config user.email)" -f gh-pages -N ""此时会在当前目录下生成两个文件:
gh-pages 和 gh-pages.pub,分别为私钥和公钥。添加Deploy Key
在 
EXAMPLE.github.io 的 Settings -> Deploy keys -> Add deploy key 中添加公钥 gh-pages.pub,Allow write access 勾选。在 
EXAMPLE-BLOG 的 Settings -> Secrets -> New repository secret 中添加私钥 gh-pages,命名为 ACTIONS_DEPLOY_KEY。配置 Github Actions
此处会使用到第三方的Actions:peaceiris/actions-gh-pages
同时因为我的博客使用了主题,这里采用
submodules的方式引入主题,所以需要在checkout时加上submodules: true。1name: Build-Pages
2
3on:
4  push:
5    branches:
6      - main
7
8jobs:
9  pages:
10    runs-on: ubuntu-latest
11    permissions:
12      contents: write
13    steps:
14      - uses: actions/checkout@v3
15        with:
16          submodules: true
17      - name: Use Node.js 16.x
18        uses: actions/setup-node@v2
19        with:
20          node-version: '16.18.1'
21      - name: Cache NPM dependencies
22        uses: actions/cache@v2
23        with:
24          path: node_modules
25          key: ${{ runner.OS }}-npm-cache
26          restore-keys: |
27            ${{ runner.OS }}-npm-cache
28      - name: Install Dependencies
29        run: npm install
30      - name: Build
31        run: npm run build
32      - name: Deploy
33        uses: peaceiris/actions-gh-pages@v3
34        with:
35          deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
36          external_repository: EXAMPLE/EXAMPLE.github.io
37          publish_dir: ./public
38          user_name: 'github-actions[bot]'
39          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的环境也可以写博客了,或许会让我写博客的频率更高一些吧~