Github Action自动化部署Hexo


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

SSH 秘钥


ssh-keygen -f hexo-deploy-key -t rsa -C ""

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

  • 页面文件仓库(即 在 Settings > Deploy keys 中添加 Deploy key,内容为 文件内容,同时勾选 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
# Triggers the workflow on push or pull request events but only for the main branch
branches: [ main ]

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

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
# This workflow contains a single job called "build"
# 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
# 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
node-version: '14'

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

- name: Set Key
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan >> ~/.ssh/known_hosts
git config --global ""
git config --global "yourname"

- name: Hexo Deploy
run: |
hexo clean
hexo generate
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”