alanwilter
alanwilter

Reputation: 582

github action yaml: how to refer an item in a matrix array?

That's my matrix:

jobs:
   check-test:
      runs-on: ubuntu-latest
      strategy:
         matrix:
            python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"]

And I have this current conditional (that's working):

          if: matrix.python-version == 3.6

How can I replace 3.6 by the first item of my matrix? I mean, how to tell in yaml:


if: matrix.python-version == "the_first_item_from_matrix.python-version"

And no, matrix.python-version[0] (or [1], I don't know how it's indexed) won't work.

The reasoning here is: in some point I will drop 3.6 support and I don't want to remember to remove any 3.6 hardcoded in my workflow.

Upvotes: 3

Views: 904

Answers (1)

trallnag
trallnag

Reputation: 2386

I propose a simple workaround using the strategy.job-index property. According to the documentation, this property is defined as follows:

The index of the current job in the matrix. Note: This number is a zero-based number. The first job's index in the matrix is 0.

You can use this property to ensure that a step is only executed for the first job in the matrix.

Here is a minimal workflow to demonstrate the idea:

name: demo
on:
  push:
jobs:
  demo:
    strategy:
      fail-fast: false
      matrix:
        python-version: ['3.7', '3.10']
    runs-on: ubuntu-latest
    steps:
      - if: strategy.job-index == 0
        run: echo '3.7' && exit 1

      - if: strategy.job-index == 1
        run: echo '3.10' && exit 1

Here are screenshots to show the result:

enter image description here

enter image description here

Sadly this workaround will get more complicated once we start to work with a matrix that has more than one dimension.

Upvotes: 1

Related Questions