Github Actions 自动化部署 Hexo
3 min read
上一次使用 Gtihub Actions 还是用在 TenAPI Docs 项目,通过 Actions 自动化编译 VuePress,不过目前每次更新文章到也不是很麻烦,直接两条命令完事。
hexo n 'title' # 新建文章
hexo g -d # 编译部署
但是目前的痛点就是:每次终端和 Github 通信都需要开一下代理,而不像浏览器设置了分流规则… 其次就是面临备份的问题,所以干脆全套迁移线上了。
创建仓库
这里我们需要创建两个仓库
- Blog - 私有仓库,用来存储你博客文件
- [username].github.o - 公有仓库,用来存储编译后的博客文件及 Github Pages
生成公私钥
使用 CMD 执行以下命令,会在当前目录生成公私钥:hexo-action.pub 和 hexo-action
ssh-keygen -t rsa -b 4096 -C "$(git config user.email)" -f hexo-ation -N ""
配置Deploy Key
在 <username>.github.io 的 Settings -> Deploy keys -> Add deploy key 中添加公钥 hexo-action.pub,Allow write access 勾选,地址如下
https://github.com/<usernmae>/<repo>.github.io/settings/keys
在 Blog 的 Settings -> Secrets -> Secrets and variables -> actions -> New repository secret 中添加私钥 hexo-action,同时命名为 ACTIONS_DEPLOY_KEY。具体地址如下
https://github.com/<usernmae>/<repo>/settings/secrets/actions
配置Github Actions
这里主要用的 actions-gh-pages 作为 Actions ,大家唯一需要修改的地方为部署仓库: external_repository 和提交分支:publish_branch 配置项。同时当 Blog 仓库的 main 分支(配置项:branches)发生 pull 时候将自动触发 Actions,将以下内容存放到 .github/workflows/deployment.yml 文件内即可。
name: Hexo-Build-Pages
on:
push:
branches:
- main
jobs:
pages:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v3
with:
submodules: true
- name: Use Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: '16.18.1'
- name: Install Dependencies
run: npm install
- name: Build
run: npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
external_repository: <username>/<usernmae>.github.io
publish_dir: ./public
publish_branch: master
force_orphan: true
keep_files: false
user_name: 'github-actions[bot]'
user_email: 'github-actions[bot]@users.noreply.github.com'
目录总览
最终 Blog 仓库目录结构大致如下
Blog
├─ .github
│ └─ workflows
│ └─ deployment.yml
├─ .gitignore
├─ _config.yml
├─ db.json
├─ package.json
├─ source
└─ themes