博客自动发布
为了方便可以使用 GitHub Actions 实现博客自动发布,将静态博客页面部署到多个服务器上,比如 GitHub Pages,Gitee pages 以及云服务器上。本文介绍使用 GitHub Actions 实现将 Hexo 博客自动编译并发布到 GitHub Pages 上。GitHub Actions 是一个自动化工作流程系统,允许用户在GitHub上定义各种自动化任务,如构建、测试、打包、部署等。
流程
SSH 秘钥
生成秘钥用于仓库间的推送:
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 创建新的工作流,配置内容如下:
name: Deploy
on: [push]
jobs:
build:
runs-on: ubuntu-latest
name: A job to deploy blog.
steps:
- name: Checkout
uses: actions/checkout@v1
with:
submodules: true # Checkout private submodules(themes or something else).
# Caching dependencies to speed up workflows. (GitHub will remove any cache entries that have not been accessed in over 7 days.)
- name: Cache node modules
uses: actions/cache@v1
id: cache
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: npm ci
# Deploy hexo blog website.
- name: Deploy
id: deploy
uses: sma11black/hexo-action@v1.0.3
with:
deploy_key: ${{ secrets.DEPLOY_KEY }}
user_name: haoqi7 # (修改为自己的用户名)
user_email: w00989988@gmail.com # (修改为自己的邮箱地址)
commit_msg: ${{ github.event.head_commit.message }} # (or delete this input setting to use hexo default settings)
# Use the output from the `deploy` step(use for test action)
- name: Get the output
run: |
echo "${{ steps.deploy.outputs.notify }}"
下面是该配置文件的逐行解析:
name: Deploy: 定义工作流的名称为”Deploy”,意指部署操作。on: [push]: 指定触发该工作流的事件为push,即当仓库有新的推送时自动执行此工作流。
接下来是定义了一个名为build的job(任务):
runs-on: ubuntu-latest: 指定执行此job的操作系统环境为最新版本的Ubuntu。name: A job to deploy blog.: 给这个job命名,说明这是一个部署博客的任务。
job中包含了一系列steps(步骤):
Checkout: 使用
actions/checkout@v1Action检出代码库,确保工作目录包含了即将部署的内容。with.submodules: true表示同时检出子模块,适用于依赖私有主题或其他子模块的情况。Cache node modules: 利用
actions/cache@v1Action来缓存node_modules目录,以加速后续工作流程。通过hashFiles('**/package-lock.json')生成缓存的键,确保依赖更新时能正确重建缓存。如果找到匹配的缓存,则跳过安装依赖的步骤。Install Dependencies: 当缓存未命中时,运行
npm ci命令安装项目依赖。这是在Node.js项目中快速且确定性地安装依赖的方式。Deploy: 使用
sma11black/hexo-action@v1.0.3这个自定义Action部署Hexo博客。需要提供部署密钥(通过${{ secrets.DEPLOY_KEY }}安全获取)、用户名、邮箱以及提交信息。这些信息用于将本地构建好的站点推送到远程服务器或托管服务。Get the output: 最后一步是获取部署步骤(
deploy)的输出信息(如果有的话),这里仅用于示例中输出部署通知信息到日志中。
整个工作流旨在实现自动化部署Hexo博客的过程,包括代码检出、依赖管理、以及最终的部署操作,充分利用了GitHub Actions的灵活性和效率。