GitHub Actions – publishing changes to a branch

If you want to do something like GitHub pages does with Jekyll, i.e. takes master and generates the website and then publishes the resultant files to the gh-pages branch, then you’ll need to set-up personal access tokens and use them in your GitHub action, for example

  • Go to Personal access tokens
  • Click on the “Generate new token” button
  • In the Note field, give it a descriptive name so you know the purpose of the token
  • If you’re wanting to interact with the repo (as we want to for this example) then check the repo checkbox to enable all repo options
  • Click the “Generate token” button
  • Copy the generated token for use in the next section

Once we have a token we’re going to use this in our repositories. So assuming you have a repo created, do the following to store the token

  • Go to your repository and click the “Settings” tab
  • Select the “Secrets<" option
  • Click on the “New secret” button
  • Give the secret a name, for example PUBLISH_TOKEN
  • Paste the token from the previous section in the “Value” textbox
  • Finally click the “Add secret” button

This now stores the token along with the name/key, which can then be used in our GitHub action .yml files, for example here’s a snippet of a GitHub action to publish a website that’s stored in master to the gh-pages branch.

- name: GitHub Pages Publish
  if: ${{ github.ref == 'refs/heads/master' }} 
    uses: peaceiris/actions-gh-pages@v3.6.1
    with:
      github_token: ${{ secrets.PUBLISH_TOKEN }}
      publish_branch: gh-pages
      publish_dir: ./public

In this example action, we check for changes on master, then use GitHub Actions for GitHub Pages to publish to the gh-pages branch from the ./public folder on master. Notice we use the secrets.PUBLISH_TOKEN which means GitHub actions will supply the token from our secrets setting using the name we gave for the secret.

Obviously this example doesn’t build/generate or otherwise do anything with the code on master, it simply takes what’s pushed to master/public and publishes that to the gh-pages branch. Ofcourse if we combine this action with previous build/generate steps as part of a build pipleline.