Skip to content

Instantly share code, notes, and snippets.

@gerrowadat
Last active December 5, 2023 04:17
Show Gist options
  • Save gerrowadat/cced52101ed0f739c2ad9c7b7eac2534 to your computer and use it in GitHub Desktop.
Save gerrowadat/cced52101ed0f739c2ad9c7b7eac2534 to your computer and use it in GitHub Desktop.
Publishing a hugo webroot to a GCS bucket

The live version of this is in the andvarienterprises/www.strategichopes.co repo.

First, you'll need a gcloud project that has storage enabled. This is pretty easy to do, the free quota should cover you for a while. In my example, I create a bucket based on a domain I own, you'll need to verify ownership of a domain if you do similar, or try your luck with the global(!) bucket namespace otherwise.

Then, the commands to set up your bucket and a service account that has access to it looks something like:

# Set up with bucket-level access control and public reads.
gcloud storage buckets create gs://MYBUCKET/ \
  --uniform-bucket-level-access \
  --no-public-access-prevention

# Create a service account just for updating.
gcloud iam service-accounts create MYNEWACCOUNT

# Give MYNEWACCOUNT access to update
gcloud storage buckets add-iam-policy-binding gs://MYBUCKET/ \
  --member=serviceAccount:MYNEWACCOUNT@${MYPROJECT}.iam.gserviceaccount.com \
  --role=roles/storage.legacyBucketOwner

# generate a JSON key because I've yet to bother with the other way.
gcloud iam service-accounts keys create key.json \
    --key-file-type=json \
    --iam-account=MYNEWACCOUNT@${PROJECT}.iam.gserviceaccount.com

# Flatten the key for use as a github secret. 
cat key.json | jq -r tostring > key.flat.json

Load the key into your repo as a repo-level secret (Settings->Secrets and Variables->Actions) called something like GCLOUD_JSON_KEY (or whatever).

Next, add your action. Add the following to .github/workflows/hugo-deploy.yml (or whatever).

name: Hugo build-on-change deploying to gcloud storage bucket
on:
  workflow_dispatch:
  push:
    branches:
      - main
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: 'read'
      id-token: 'write'
    steps:
    - uses: actions/checkout@v4
    - uses: jakejarvis/hugo-build-action@v0.111.3
      with:
        args: --minify --buildDrafts
    - id: 'google-auth'
      uses: 'google-github-actions/auth@v1'
      with:
        service_account: 'MYNEWACCOUNT@MYPROJECT.iam.gserviceaccount.com'
        credentials_json: ${{ secrets.GCLOUD_JSON_KEY }}
    - id: 'upload-folder'
      uses: 'google-github-actions/upload-cloud-storage@v1'
      with:
        path: 'public'
        destination: 'MYBUCKET'
        parent: false

Et voila. Whenever you commit a change to the hugo site in the repo, a built version should appear in the GCS bucket. You can then serve your website from there, if you so choose!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment