Github Action实现Blog自动发布

密钥对接流程

使用 Hexo 的 Git 部署方式将生成的静态文件推送到 GitHub Pages 的 gh-pages 分支,但没有成功。这种情况下,通常需要检查以下几个关键点:

1. 确保 SSH 密钥正确配置

由于你使用的是 SSH 地址(git@github.com:owen-chenao/owen-chenao.github.io.git),需要确保 GitHub Actions 有权限通过 SSH
推送到目标仓库。

解决方法

  1. 生成 SSH 密钥对: 在本地生成一个 SSH 密钥对,公钥需要添加到目标仓库的 Deploy Keys 中。

    bash

    复制

    1
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f deploy_key

这将生成 deploy_key(私钥)和 deploy_key.pub(公钥)。

  1. 将公钥添加到目标仓库的 Deploy Keys

    • 打开目标仓库(owen-chenao.github.io)的 Settings 页面。
    • 在左侧菜单中选择 Deploy keys
    • 点击 Add deploy key,将 deploy_key.pub 的内容粘贴进去,并勾选 Allow write access
  2. 将私钥添加到 GitHub Actions 的 Secrets

    • 打开源仓库(owen_private_blog)的 Settings 页面。
    • 在左侧菜单中选择 Secrets and variables > Actions
    • 点击 New repository secret,名称为 DEPLOY_KEY,值为 deploy_key 的内容(私钥)。
  3. 修改 deploy.yml 文件: 在 GitHub Actions 的工作流中,需要使用私钥来配置 SSH 代理,以便能够通过 SSH 推送到目标仓库。以下是修改后的
    deploy.yml 文件:

    yaml

    复制

    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
    name: Deploy Hexo to GitHub Pages

    on:
    push:
    branches:
    - main

    jobs:
    deploy:
    runs-on: ubuntu-latest
    permissions:
    contents: write
    steps:
    - name: Checkout blog source
    uses: actions/checkout@v3
    with:
    fetch-depth: 0

    - name: Set up Node.js
    uses: actions/setup-node@v3
    with:
    node-version: "18"

    - name: Cache dependencies
    uses: actions/cache@v3
    with:
    path: node_modules
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
    restore-keys: ${{ runner.os }}-node-

    - name: Install dependencies
    run: npm install

    - name: Generate Hexo site
    run: npx hexo generate

    - name: Set up SSH agent
    uses: webfactory/ssh-agent@v0.5.4
    with:
    ssh-private-key: ${{ secrets.DEPLOY_KEY }}

    - name: Deploy to GitHub Pages
    run: |
    git config --global user.name "github-actions"
    git config --global user.email "github-actions@github.com"
    npx hexo deploy

在这里,我们使用了 webfactory/ssh-agent 动作来设置 SSH 代理,并将私钥传递给它。

2. 确保 Hexo 配置正确

在 Hexo 的 _config.yml 文件中,确保部署配置正确:

yaml

复制

1
2
3
4
deploy:
type: git
repo: git@github.com:owen-chenao/owen-chenao.github.io.git
branch: gh-pages

3. 确保目标仓库的 GitHub Pages 配置正确

  1. 打开目标仓库(owen-chenao.github.io)的 Settings 页面。
  2. 在左侧菜单中选择 Pages
  3. Source 部分,选择 gh-pages 分支作为发布源。

过程图片记录

私有库(owen_private_blog)

配置Actions secrets and variables

https://github.com/owen-chenao/owen_private_blog/settings/secrets/actions

公有库配置SSH(owen-chenao.github.io)

https://github.com/owen-chenao/owen-chenao.github.io/settings/keys

Action操作执行步骤和结果