title: GitHub Actions实现博客自动发布
author: HaoQi
top: false
cover: false
toc: true
mathjax: false
categories:

  • 博客篇

tags:

  • hexo
  • GitHub Actions

summary: 为了方便可以使用 GitHub Actions 实现博客自动发布,将静态博客页面部署到Github Pages。
reprintPolicy: cc_by
coverlmg:
img:
date: 2022-03-17 10:10:46


前言

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

流程

SSH 秘钥

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

  1. ssh-keygen -f hexo-deploy-key -t rsa -C "个人邮箱"

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

页面文件仓库(即 haoqi7.github.io): 在 Settings > Deploy keys 中添加 Deploy key,名称为deploy_key内容为 hexo-deploy-key.pub 文件内容,同时勾选 Allow write access 选项。
博客源文件库:在 Settings > Secrets 中添加一个 Secret,名称为 DEPLOY_KEY,内容为 hexo-deploy-key 文件内容。后续在 Workflow 中通过名称 DEPLOY_KEY 使用这个密钥。

Workflow 配置

在博客源文件库中点击actions创建新的工作流,配置内容如下:

  1. name: Deploy
  2. on: [push]
  3. jobs:
  4. build:
  5. runs-on: ubuntu-latest
  6. name: A job to deploy blog.
  7. steps:
  8. - name: Checkout
  9. uses: actions/checkout@v1
  10. with:
  11. submodules: true # Checkout private submodules(themes or something else).
  12. # Caching dependencies to speed up workflows. (GitHub will remove any cache entries that have not been accessed in over 7 days.)
  13. - name: Cache node modules
  14. uses: actions/cache@v1
  15. id: cache
  16. with:
  17. path: node_modules
  18. key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
  19. restore-keys: |
  20. ${{ runner.os }}-node-
  21. - name: Install Dependencies
  22. if: steps.cache.outputs.cache-hit != 'true'
  23. run: npm ci
  24. # Deploy hexo blog website.
  25. - name: Deploy
  26. id: deploy
  27. uses: sma11black/hexo-action@v1.0.3
  28. with:
  29. deploy_key: ${{ secrets.DEPLOY_KEY }}
  30. user_name: haoqi7 # (修改为自己的用户名)
  31. user_email: w00989988@gmail.com # (修改为自己的邮箱地址)
  32. commit_msg: ${{ github.event.head_commit.message }} # (or delete this input setting to use hexo default settings)
  33. # Use the output from the `deploy` step(use for test action)
  34. - name: Get the output
  35. run: |
  36. echo "${{ steps.deploy.outputs.notify }}"