GitHub Actions部署Hexo到远程服务器

本教程只说实操不说原理,需要你对 GitHub Actions 有一定的了解。

一、大概步骤

  1. 创建 GitHub 账号
  2. 创建放博客的私有仓库
  3. 创建工作流文件
  4. 获取服务器 SSH 密钥
  5. 创建 secret
  6. 提交代码
  7. 验证

步骤1和步骤2比较简单,在此省略。

二、详细步骤

2.3 创建工作流文件

博客根目录下创建一个文件: .github/workflows/deploy.yml 文件,deploy.yml 文件名任意,但必须是 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 当有改动推送到main分支时,启动Action
name: Hexo博客自动部署

on:
push:
branches:
- main

release:
types:
- published

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 检查分支
uses: actions/checkout@v2
with:
ref: main

- name: 安装 Node
uses: actions/setup-node@v1
with:
node-version: "18.x"

- name: 安装 Hexo
run: |
export TZ='Asia/Shanghai'
npm install hexo-cli -g

- name: 缓存 Hexo
id: cache-npm
uses: actions/cache@v3
env:
cache-name: cache-node-modules
with:
path: node_modules
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-

- name: 安装依赖
if: ${{ steps.cache-npm.outputs.cache-hit != 'true' }}
run: |
npm install --save

- name: 生成静态文件
run: |
hexo clean
hexo bangumi -u #bilibili番剧更新
hexo generate

- name: 部署
uses: burnett01/rsync-deployments@6.0.0
with:
switches: -avzr --delete
path: public/
remote_path: ${{ secrets.DEPLOY_PATH }}
remote_host: ${{ secrets.DEPLOY_HOST }}
remote_port: ${{ secrets.DEPLOY_PORT }}
remote_user: ${{ secrets.DEPLOY_USER }}
remote_key: ${{ secrets.DEPLOY_KEY }}

文件的 uses 如果有问题,工作流将不会执行,所以你可以在 GitHub 中去编辑,如果没有爆红则没问题。
解决方法是去 官方市场 搜索对应的 action,替换或者更新版本。

$ 这些变量是在仓库的中配置的,下面做介绍。

remote_path: 部署目标路径
remote_host: 远程主机
remote_port: 远程端口,默认为 22
remote_user: 远程用户
remote_key: 远程 ssh 密钥

2.4 获取服务器 SSH 密钥

远程服务器执行以下命令

1
2
ssh-keygen // 会在 ~/.ssh 生成公钥和私钥 id_rsa.pub、id_rsa
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys // 将公钥 id_rsa.pub 复制到 authorized_keys

复制私钥 id_rsa 内容

2.5 创建 secret

创建5个 secret,对应步骤3里的五个值,密钥已经在步骤4获取到了。

创建 secret_1

2.6 提交代码

注意如果你有想要装的第三方 npm 包,需要在步骤3的工作流文件中写入。

2.7 验证

验证_1