0%

使用 Github Actions 自动部署 Hexo 博客

写在前面:

使用 Hexo 进行博客写作非常方便:

  1. hexo new post "TITLE" 新建文章
  2. hexo g 生成静态页面
  3. hexo d 部署页面

美中不足的是,一旦切换写作环境或者数据丢失,原始的文章及相关配置难以同步备份。

对于需要备份的文档等小体积文件,较为通用的做法是使用 Git 进行版本控制,并托管项目到免费开放平台,如 Github, Gitee, Gitlab 等。

懒,是第一生产力!

那么,对于博客写作来说,在提交新改动后,自动化 发布文章是更便捷的做法。

使用 Github Actions 自动化部署博客

Github Actions 介绍

Github Actions 是 Github 推出的持续集成/持续交付或部署 (CI/CD)工具。它能够与 Github 上的项目无缝结合,十分好用。

GitHub Actions enables you to create custom software development life cycle (SDLC) workflows directly in your GitHub repository.

GitHub Actions 可以让你直接在 GitHub 仓库中创建自定义的软件开发生命周期 (SDLC) 工作流程。

Github Actions 有很丰富的玩法,如:自动化构建基于项目的 Docker 镜像并发布,自动编译最新的 LEDE 固件等。

本篇仅介绍使用 Github Actions 自动发布博客文章。

相关配置与用法

首先生成 RSA 非对称密钥对:

ssh-keygen -t rsa -b 4096 -C 'YourEmail' -f "DEPLOY_KEY"

复制公钥,并在博客文章对应的 repo (xxx.github.io) 里填写:repo => settings => Deploy keys,命名随意

clip < DEPLOY_KEY.pub

复制私钥,并在博客项目对应的 repo 里填写:repo => settings => secrets, 并命名为 DEPLOY_KEY

clip < DEPLOY_KEY

在博客项目下,初始化 git 仓库:git init ,并与 Github 上的远程仓库连接:git remote add origin YourRepoURL(建议设置为私密仓库)

创建并编辑 ./github/workflows/actions.yml文件:

# ./github/workflows/actions.yml
name: Deploy Hexo

on:
push:
branches:
- master

jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1

- name: Setup Node.js environment
uses: actions/setup-node@v2-beta
with:
node-version: '12'

- name: Install pandoc (Latex support)
run: |
wget -O pandoc.deb https://github.com/jgm/pandoc/releases/download/2.11.1/pandoc-2.11.1-1-amd64.deb
sudo dpkg -i pandoc.deb

- name: Set git environment
env:
# 1. Add this private key and title as DEPLOY_KEY in this repo -> settings/secrets
# 2. Add corresponding public key and named as any text to the github page repo -> settings/deploy keys
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
USERNAME: YourUsername!CHANGEME
EMAIL: YourEmail!CHANGEME
run: |
mkdir -p ~/.ssh/
echo "$DEPLOY_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.name "$USERNAME"
git config --global user.email "$EMAIL"

- name: Setup Hexo environment
run: |
npm install -g hexo-cli
npm install

- name: Deploy Hexo
run: |
hexo g
hexo d

在创建或者改动文章及配置后,使用 git 进行提交,并推送至远程 master 分支:

git add .
git commit -m "Update ..."
git push -u origin master

在远程仓库接收到推送后,Github Actions 会进入该工作流,按照设定更新博客文章。

注:

  1. 在项目的 _config.yml 需把 Git 的 repo地址设置为 SSH 格式:[email protected]:YourName/YourRepo.git,使用 HTTPS 格式的 repo 地址会造成部署失败。
  2. 如果主题模板目录含有 .git 文件夹,需删除该目录,否则会造成渲染静态页面失败。

延伸阅读

Github Actions 官方文档 (可选中文)

actions.yml 持久更新链接