Hugo: How To Use GitHub Actions To Push to a Remote Repository

As you may have read previously, I use Hugo for this blog. It’s a simple Markdown to static website generator with some sleek free themes. Makes it easy for me! But I wanted to polish up the workflow on how I generate content, vs writing it in my code editor. So I stumbled across https://app.forestry.io/

The Workflow

So how does it work? Well I signed up for an account on forestry. It connects to my private Github repo where markdown files, templates etc are stored. When I write an article, Forestry pushes these changes via a git commit to the Github repo.

From there I have a github action that runs on this repo with these changes. It runs a Hugo run, generates SSH keys to the environment, then pushes these static files to a separate repo which is public and only stores these static files.

This way I keep the blog and potentially sensitive material and drafts offline, only exposing public material in the public repo.

The Action

So the magic was in getting Github to talk to itself. The private repo with the markdown files has the Github action to generate the flat files, commits them to a branch, then I just want to publish that branch, only, to a public repo.

The GitHub action looks like this:

name: GitHub Pages

on:
  push:
    branches:
      - main  # Set a branch to deploy
  pull_request:

jobs:
  deploy:
    runs-on: ubuntu-20.04
    concurrency:
      group: ${{ github.workflow }}-${{ github.ref }}
    steps:
      - uses: actions/checkout@v2
        with:
          submodules: true  # Fetch Hugo themes (true OR recursive)
          fetch-depth: 0    # Fetch all history for .GitInfo and .Lastmod

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: '0.91.2'
          # extended: true

      - name: Build
        run: hugo --minify

      - name: Create SSH key
        run: |
          mkdir ~/.ssh/
          cd ~/.ssh
          echo "$SSH_PRIVATE_KEY" > id_rsa
          pwd
          sudo chmod 600 id_rsa
          echo "$SSH_KNOWN_HOSTS" > known_hosts
        shell: bash
        env:
          SSH_PRIVATE_KEY: ${{secrets.SSH_PRIVATE_KEY}}
          SSH_KNOWN_HOSTS: ${{secrets.SSH_KNOWN_HOSTS}}
          SSH_KEY_PATH: ${{ github.workspace }}/../private.key

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        if: ${{ github.ref == 'refs/heads/main' }}
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./public

      - name: Deploy Files
        run: |
          git remote add www [email protected]:voidet/jotlab-www.git
          git fetch www
          git push -u www gh-pages:main

Store your SSH_PRIVATE_KEY in Github Secrets for this repo, as well as your SSH_KNOWN_HOSTS file. I just used the same one stored on my laptop. It works.