Github Action自动化部署Hexo

引言

为了方便可以使用 GitHub Actions 实现博客自动发布,将静态博客页面部署到多个服务器上,比如 GitHub Pages,Gitee pages 以及云服务器上。本文介绍使用 GitHub Actions 实现将 Hexo 博客自动编译并发布到 GitHub Pages 上。

SSH 秘钥

生成秘钥用于仓库间的推送:

ssh-keygen -f hexo-deploy-key -t rsa -C "youremail@something.com"

以上命令会在当前路径下生成:秘钥 hexo-deploy-key 和公钥 hexo-deploy-key.pub,然后分别添加到对应的文件中。

  • 页面文件仓库(即 yousazoe.github.io): 在 Settings > Deploy keys 中添加 Deploy key,内容为 hexo-deploy-key.pub 文件内容,同时勾选 Allow write access 选项

  • 博客源文件库:在 Settings > Secrets 中添加一个 Secret,名称为 DEPLOY_KEY,内容为 hexo-deploy-key 文件内容。后续在 Workflow 中通过名称 DEPLOY_KEY 使用这个密钥

Workflow 配置

在博客源文件库中新建文件 .github/workflows/deploy.yml,配置内容如下:

# This is a basic workflow to help you get started with Actions

name: Blog deploy

# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the main branch
push:
branches: [ main ]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build-and-deploy:
# The type of runner that the job will run on
runs-on: ubuntu-latest

# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2

# Runs a set of commands using the runners shell
- name: Set Node
uses: actions/setup-node@v2
with:
node-version: '14'

- name: Npm Install
run: |
npm install hexo-cli -g
npm install

- name: Set Key
env:
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
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.email "yourname@mail.com"
git config --global user.name "yourname"

- name: Hexo Deploy
run: |
hexo clean
hexo generate
gulp
hexo deploy

Webhook 部署

  1. Copy the Deploy Webhook URL.

You can find your site’s deploy Webhook under the “Settings” tab.

  1. Paste the Deploy Webhook URL on “Payload URL” in your Github

Github > Settings > Webhooks > “Payload URL”

  1. Click “Add webhook”

参考文献