GitHub Actions Cheatsheet

How to structure your Github Actions’ YAML files

Jun 1, 2023 by Mikolaj Gasior



TL;DR

Naming convention

The following styles are recommended:

Workflow filenames

With many workflows it is difficult to distinguish them (this might be the case when having a big monorepo), especially when the list of their names in the UI on the Actions page is very narrow, and when many of them “build” something. Hence, it is good to decide on the terminology, like use “build binary” verb for binaries, “build image” for docker images, “push” for pushing them, “store” for saving in a specific place etc. and use these keywords within the whole code. Any naming is probably good if it is just consistent. It saves some characters, if “image” is always a docker image then there is no reason to add “docker”.

There are many ways to name the workflows files. One of them is to always use the verb, like build-and-push-xyz.yml, deploy-to-devenv.yml and so on. Another one is based on the event, like on-pr-commit.yml, on-pr-label.yml, on-main-branch-commit.yml etc. Both look quite straight forward.

Last thing to mention is to DRY and extract the code to sub-workflows. To not confuse them with normal workflows, just prefix their filenames with an underscore _ or something.

github-actions-validator

See the list here of what check this tool can run. It can save your team some time whilst reviewing changes, just add the tool as a separate workflow that is triggered on any pull request commit. Check sample action below. Feel free to modify the dummy bash script.

---
name: GitHub Actions Validator
description: Validate YAML actions

runs:
  using: "composite"
  steps:
    - name: Checkout source code
      uses: actions/checkout@v3

    - name: Run github-actions-validator
      env:
        DOCKER_IMAGE: mikogs/github-actions-validator:v0.4.3
      shell: bash
      run: |
        set +e
        docker pull ${DOCKER_IMAGE}
        docker run --rm --name tmp-ghv -v $(pwd)/.github:/dot-github \
          -v $(pwd)/tmp-vars-list.txt:/tmp-vars-list.txt \
          -v $(pwd)/tmp-secrets-list.txt:/tmp-secrets-list.txt \
          ${DOCKER_IMAGE} \
          validate -p /dot-github > validation_result
        echo "------------------------------------------------"
        cat validation_result
        echo "------------------------------------------------"
        cat validation_result | grep '^E' > validation_result_errors
        if [[ $(cat validation_result_errors | wc -l) > 0 ]]; then
          echo "!!! Errors have been found in GitHub YAML files!"
          echo "------------------------------------------------"
          cat validation_result_errors
          echo "------------------------------------------------"
          echo "!!! Please fix them!"
          exit 1
        fi

YAML linter

Create a .yamllint file with a set of rules for YAML files and add a workflow with any yaml lint action out there on github to lint your .github files.