How to avoid code duplication in Github Actions; are there some kind of loops in yaml?

Could this have been done shorter with some kind of a loop or wildcard?

Yes, but not without investing some time to write code, which will probably cause you more work than it will save you.

GitHub Actions itself does not support anything like loops according to the official documentation. This means that if you want to shorten the file, you need to write the code expanding the file yourself and apply it to the file before using it with GitHub Actions.

You could go the way several other YAML-based tools (e.g. Ansible) go and use Python's Jinja2 templating engine to write loops. However, this is very awkward since you'll need to escape the GH Actions expressions as they use similar syntax.

Probably a better way to go would be to create the data structure in Python (or any other scripting language that has YAML support) and dump it as YAML.

I wouldn't recommend any of those approaches because of the entropy they add to your setup but it's definitely possible.


Github actions support both wildcards and loops. Examples below were copied from the docs.

Wildcard example

'**/migrate-*.sql'

A file with the prefix migrate- and suffix .sql anywhere in the repository.

Matches:

  • migrate-10909.sql
  • db/migrate-v1.0.sql
  • db/sept/migrate-v1.sql

more wildcard examples: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#patterns-to-match-file-paths

Loop Example (matrix)

This one runs the step 3 times, one with each value of the node variable:

strategy:
  matrix:
    node: [6, 8, 10]
steps:
  # Configures the node version used on GitHub-hosted runners
  - uses: actions/setup-node@v1
    with:
      # The Node.js version to configure
      node-version: ${{ matrix.node }}

other examples using matrix: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix