LOADING

加载过慢请开启缓存 浏览器默认开启

Automate Hexo Deployment to GitHub Pages with GitHub Actions

Automate Hexo Deployment to GitHub Pages with GitHub Actions: A Comprehensive tutorial

Deploying a static website generated by Hexo to GitHub Pages can be seamlessly automated using GitHub Actions. This tutorial will guide you through setting up an automated workflow that:

  1. Generates your Hexo site every time you push changes to your repository.
  2. Deploys the generated static files to the docs folder of a separate GitHub Pages repository, enabling continuous updates to your website.

By the end of this guide, you’ll have a fully automated CI/CD pipeline for your Hexo blog, ensuring your website remains up-to-date with your latest content without manual intervention.

Table of Contents

  1. Prerequisites
  2. Generating a Personal Access Token (PAT)
  3. Adding the PAT to GitHub Secrets
  4. Setting Up the GitHub Actions Workflow
  5. Configuring GitHub Pages in the Target Repository
  6. Testing the Workflow
  7. Troubleshooting Common Issues
  8. Conclusion

Prerequisites

Before you begin, ensure you have the following:

  • Two GitHub Repositories:

    • Source Repository: Your primary repository containing the Hexo blog source code (e.g., YourUsername/YourBlog).
    • Target Repository: Your GitHub Pages repository where the static site will be deployed (e.g., YourUsername/YourBlog.github.io).
  • Hexo Installed and Configured: Ensure your Hexo blog is properly set up and can generate static files locally using hexo generate.

  • Basic Knowledge of GitHub Actions: Familiarity with creating and editing YAML files within GitHub repositories will be beneficial.


Generating a Personal Access Token (PAT)

To allow GitHub Actions to push changes to your target repository, you need a Personal Access Token (PAT) with the appropriate permissions.

Steps to Generate a PAT:

  1. Log in to GitHub:

    • Navigate to GitHub and sign in to your account.
  2. Access Developer Settings:

    • Click on your profile picture in the top-right corner.
    • Select Settings from the dropdown menu.
    • In the left sidebar, click on Developer settings.
  3. Create a New Token:

    • Click on Personal access tokens.
    • Click the Generate new token button.
  4. Configure the Token:

    • Note: Enter a descriptive name, e.g., GitHub Actions Deploy Token.
    • Expiration: Choose an appropriate expiration date. For security reasons, it’s recommended not to set it to never expire.
    • Scopes:
      • Expand the repo section.
      • Select repo (all sub-scopes under repo will be automatically selected), ensuring the token has full control of private repositories.
  5. Generate and Copy the Token:

    • Click Generate token.
    • Important: Copy the generated token immediately. You won’t be able to view it again.

Adding the PAT to GitHub Secrets

To securely use your PAT within GitHub Actions, store it as a secret in your source repository.

Steps to Add the PAT as a Secret:

  1. Navigate to Your Source Repository:

    • Go to YourUsername/YourBlog on GitHub.
  2. Access Repository Settings:

    • Click on the Settings tab.
    • In the left sidebar, select Secrets and variables > Actions.
  3. Add a New Secret:

    • Click on the New repository secret button.
    • Name: TARGET_REPO_TOKEN
    • Value: Paste the PAT you generated earlier.
    • Click Add secret to save.

Setting Up the GitHub Actions Workflow

With the PAT in place, you can now create a GitHub Actions workflow that automates the Hexo build and deployment process.

Steps to Create the Workflow:

  1. Create the Workflow File:

    • In your source repository (YourUsername/YourBlog), navigate to the .github/workflows/ directory. If it doesn’t exist, create it.
    • Inside the workflows folder, create a new file named deploy.yml.
    YourBlog/
    └── .github/
        └── workflows/
            └── deploy.yml
    
  2. Define the Workflow Configuration:

    • Open deploy.yml and add the following content:
    name: Deploy Hexo to GitHub Pages
    
    on:
      push:
        branches:
          - main  # Change this if your default branch is different
    
    jobs:
      build-and-deploy:
        runs-on: ubuntu-latest
    
        steps:
          # Step 1: Checkout the Source Code
          - name: Checkout Source Code
            uses: actions/checkout@v3
    
          # Step 2: Set Up Node.js Environment
          - name: Setup Node.js
            uses: actions/setup-node@v3
            with:
              node-version: '16'  # Specify your Node.js version
    
          # Step 3: Install Dependencies
          - name: Install Dependencies
            run: npm install
    
          # Step 4: Generate Hexo Static Files
          - name: Generate Hexo Site
            run: |
              npx hexo clean
              npx hexo generate
    
          # Step 5: Deploy to GitHub Pages
          - name: Deploy to GitHub Pages
            uses: peaceiris/actions-gh-pages@v4
            with:
              github_token: ${{ secrets.TARGET_REPO_TOKEN }}
              publish_dir: ./public
              destination_dir: docs
              publish_repo: YourUsername/YourBlog.github.io
              publish_branch: main
              allow_empty_commit: true
    

Breakdown of the Workflow:

  • name: Assigns a name to the workflow (Deploy Hexo to GitHub Pages).

  • on:

    • push: Specifies that the workflow runs on push events.
    • branches: The workflow triggers when there’s a push to the main branch. Adjust this if your default branch is different (e.g., master).
  • jobs:

    • build-and-deploy: The single job that builds and deploys the site.
      • runs-on: Specifies the virtual environment (ubuntu-latest).

      • steps:

        1. Checkout Source Code:

          • Uses actions/checkout@v3 to clone the repository.
        2. Setup Node.js:

          • Uses actions/setup-node@v3 to set up the Node.js environment. Adjust the node-version if your project requires a different version.
        3. Install Dependencies:

          • Runs npm install to install Hexo and other project dependencies.
        4. Generate Hexo Site:

          • Executes hexo clean to clear previous builds.
          • Runs hexo generate to build the static files, typically output to the public directory.
        5. Deploy to GitHub Pages:

          • Utilizes peaceiris/actions-gh-pages@v4, a robust action for deploying static sites.
          • github_token: References the secret TARGET_REPO_TOKEN for authentication.
          • publish_dir: Points to the directory containing the generated static files (./public).
          • destination_dir: Specifies the target directory in the repository (docs).
          • publish_repo: The target repository where the site will be deployed (YourUsername/YourBlog.github.io).
          • publish_branch: The branch to which the files will be pushed (main).
          • allow_empty_commit: Allows the workflow to run even if there are no changes to commit, preventing failures in such cases.
  1. Commit and Push the Workflow:
    • Save the deploy.yml file.

    • Commit the new workflow to your repository:

      git add .github/workflows/deploy.yml
      git commit -m "Add GitHub Actions workflow for Hexo deployment"
      git push origin main
      

Configuring GitHub Pages in the Target Repository

To ensure that GitHub Pages serves your site from the docs folder, you need to configure the settings in your target repository (YourUsername/YourBlog.github.io).

Steps to Configure GitHub Pages:

  1. Navigate to the Target Repository:

    • Go to YourUsername/YourBlog.github.io on GitHub.
  2. Access Repository Settings:

    • Click on the Settings tab.
    • In the left sidebar, select Pages.
  3. Set the Source for GitHub Pages:

    • Source:
      • Branch: Select main.
      • Folder: Choose /docs.
    • Click Save to apply the changes.
  4. Verify the Configuration:

    • After saving, GitHub will provide a URL where your site is published, typically https://YourUsername.github.io.
    • It may take a few minutes for the site to become available.

Testing the Workflow

With everything set up, it’s time to test the automated deployment process.

Steps to Test:

  1. Make a Change to Your Blog:

    • Add a new post or update existing content in your Hexo source repository (YourUsername/YourBlog).
  2. Push the Changes to GitHub:

    git add .
    git commit -m "Test deployment with a new post"
    git push origin main
    
  3. Monitor the GitHub Actions Workflow:

    • Navigate to your source repository (YourUsername/YourBlog) on GitHub.
    • Click on the Actions tab.
    • You should see a workflow run named Deploy Hexo to GitHub Pages triggered by your push.
    • Click on the workflow run to monitor its progress. Ensure all steps complete successfully.
  4. Verify the Deployment:

    • After the workflow completes, visit your GitHub Pages site at https://YourUsername.github.io.
    • Confirm that the changes reflect as expected.

Troubleshooting Common Issues

Despite following the steps carefully, you might encounter some common issues. Here’s how to address them:

1. Permission Denied (403 Error)

Error Message:

remote: Permission to YourUsername/YourBlog.github.io.git denied to github-actions[bot].
fatal: unable to access 'https://github.com/YourUsername/YourBlog.github.io.git/': The requested URL returned error: 403

Solution:

  • Ensure PAT Has Correct Permissions:

    • The PAT must have repo scope to allow push access.
    • If unsure, regenerate the PAT with repo scope and update the secret TARGET_REPO_TOKEN.
  • Verify the Secret:

    • Double-check that the TARGET_REPO_TOKEN in your source repository’s secrets is the correct PAT.
    • Ensure there are no extra spaces or hidden characters.
  • Check Repository Access:

    • Confirm that the PAT owner has write access to the target repository (YourUsername/YourBlog.github.io).

2. Unexpected Input Parameters

Error Message:

Warning: Unexpected input(s) 'folder', 'target-folder', valid inputs are ['github_token', 'repository', 'branch', 'force', 'tags', 'directory']

Solution:

  • Use Supported Inputs:
    • Ensure you’re using the correct input parameters for the GitHub Action. In this tutorial, we’re using peaceiris/actions-gh-pages@v4, which supports the necessary parameters.
    • If using a different action, refer to its documentation to confirm supported inputs.

3. Empty Commit Errors

Issue:
Sometimes, the workflow might fail if there are no changes to commit.

Solution:

  • Allow Empty Commits:
    • The allow_empty_commit: true parameter in the workflow prevents failures when there are no changes to deploy.

4. Incorrect Directory Paths

Issue:
Files are not being copied to the correct directory in the target repository.

Solution:

  • Verify publish_dir and destination_dir:
    • Ensure publish_dir points to Hexo’s output directory (./public).
    • Ensure destination_dir points to the correct folder in the target repository (docs).

5. Delayed Deployment

Issue:
Changes take longer to appear on GitHub Pages.

Solution:

  • Wait for GitHub Pages to Update:
    • GitHub Pages might take a few minutes to reflect the latest changes.
    • If delays persist, check the workflow logs for any deployment issues.

6. Authentication Issues with Actions

Issue:
The GitHub Action fails to authenticate with the target repository.

Solution:

  • Check PAT Validity:

    • Ensure the PAT hasn’t expired and is correctly stored in the repository secrets.
  • Verify Repository Names:

    • Double-check that the publish_repo field in your workflow matches the exact name of your target repository (YourUsername/YourBlog.github.io).

Conclusion

By following this comprehensive guide, you’ve set up an automated GitHub Actions workflow that:

  • Generates your Hexo site every time you push updates to your source repository.
  • Deploys the generated static files to the docs folder of your GitHub Pages repository.

This automation ensures your blog remains up-to-date without manual intervention, allowing you to focus on creating content. Additionally, using trusted actions like peaceiris/actions-gh-pages simplifies the deployment process and enhances reliability.

If you encounter any issues beyond the common ones discussed, refer to the GitHub Actions Documentation or seek assistance from the GitHub community.

Happy blogging!


References