使用 GitHub Actions 实现 Hexo 博客自动部署

使用 GitHub Actions 实现 Hexo 博客自动部署

hexo 本身就支持快捷部署的命令, 不过每次都要执行 hexo d 这个命令, 而且还要确保本地环境没有问题, 一旦换个环境又得重新配置,实属麻烦, 我们的原则是能躺着决不坐着, 加上
GitHub Actions 又是免费的, 不用白不用

工作原理

  • hexo 的源工程文件单独建立一个私有仓库
  • 每次提交完代码后触发构建
  • 让 GitHub Actions 帮我们自动执行 hexo d 命令

准备工作

    1. 首先确保你已经创建了保存工程源代码的仓库 和 GitHub Page 仓库
    1. 确定你在本地执行 hexo d 可以正常部署

生成 ssh key

ssh key 的作用是保证可以不用登陆也可以正常的 提交/拉去 代码, 因为把 用户名和密码暴露在网上是不安全的

1
ssh-keygen -t rsa -b 4096 -C "$(git config user.email)" -f hexo-deploy-key -N ""

在当前目录下生成文件:
* hexo-deploy-key # 私钥文件
* hexo-deploy-key.pub # 公钥文件

切记不要把这两个文件上传到仓库里, 避免泄露

在源代码仓库添加 私钥

在仓库页面依次点击 Settings -> Secrets -> new repository secrets, 如下图

new repository secrets

key 设置为 HEXO_DEPLOY_KEY, 当然你也可以自取, 那后面也要跟着改

示例

1
2
3
4
5
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
.......
vgpvENPs0nbwDfAAAAEWtlbmZlaUBhbGl5dW4uY29tAQ==
-----END OPENSSH PRIVATE KEY-----

在 GitHub Pages 页添加公钥

在仓库页面依次点击 Settings -> Deploye keys -> Add deploy key, 如下图

key 可以自己取, 自己认识就行, 没有影响, 这里默认就用 hexo-deploy-keys

示例

1
ssh-rsa AAAAB3Nza6pD .... ZYIVYIDyOFNmtjBZVyAXK+rKKYeC3U= xxx@aliyun.com

编写 workflows 文件

在 源代码工程目录下创建流程文件 .github/workflows/deploy.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
name: Deploy # workflow name

on:
[push] # 触发事件

jobs:
build: # job1 id
runs-on: ubuntu-latest
name: A job to deploy blog.
steps:
# 获取源码
- name: Checkout
uses: actions/checkout@v1
with:
# 签出私有子模块(主题或其他内容)
submodules: true

# 缓存压缩 node_modules,不用每次下载,使用时解压,可以加快工作流的执行过程,超过 7 天没有使用将删除压缩包。
- 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 install

# 部署 hexo 博客网站.
- name: Deploy
id: deploy
uses: sma11black/hexo-action@v1.0.0
with:
deploy_key: ${{ secrets.HEXO_DEPLOY_KEY }}
user_name: your github username
user_email: your github useremail

注意: 里面有两个需要配置的地方
user_name: 你 github 的用户名(举例: 在 https://github.com/fillpit/xxxxfillpit 就是用户名)
user_email: 你 github 的注册邮箱

Hexo 配置

查看项目根目录中 _config.yml 文件的部署相关内容:

1
2
3
4
deploy:
type: git
repo: git@github.com:fillpit/fillpit.github.io.git
branch: main

这里的repo要填写ssh的形式,千万不要使用http形式

验证

现在 Hexo 已经和 GitHub Actions 已经集成了,接下来在博客源码分支上推送代码即可自动编译部署。具体
执行过程可以在 Actions 中查看:

事故现场

出现 could not read Username for ‘https://github.com': No such device or address

解决方案: 查看 _config.yml 中的 deploy.repo 字段是不是用了 http 形式的链接, 如果是就 改成 ssh 形式的, 具体配置查看上面的 Hexo 配置

作者

坑 飞

发布于

2021-09-06

更新于

2021-09-06

许可协议

评论