0

I create the following JSON file in a python script generate_matrix.py:

output.json:

{
    "include": [
        {
            "foo": "foo1",
            "bar": "bar1",
            "path": "path1"
        },
        {
            "foo": "foo2",
            "bar": "bar2",
            "path": "path2"
        }
    ]
}

How do I trigger a reusable workflow, only if "path" == "path1"? Looks like we cannot use "if" with a matrix:

if: ${{ matrix.path }} == 'path1'

Workflow:

name: Test
on:
  push:

jobs:
  Generate_Matrix:
    runs-on: ...
    outputs:
      OUTPUT_JSON: ${{ steps.generate-matrix.outputs.OUTPUT_JSON }}
    steps:  
      ...
      - name: Generate Matrix
        id: generate-matrix
        run: |
          py -3 -E generate/generate_matrix.py
          echo "OUTPUT_JSON=$(cat output.json)" >> $env:GITHUB_OUTPUT

  Trigger_Job:
    strategy:
        matrix: ${{ fromJSON(needs.Generate_Matrix.outputs.OUTPUT_JSON) }}
    uses: ./.github/workflows/reusable-workflow.yml
    if: ${{ matrix.path }} == 'path1'
    needs:
      - Generate_Matrix
    with:
      foo: ${{ matrix.foo }}
      bar: ${{ matrix.bar }}

I get the following error:

The workflow is not valid. ...: Unrecognized named-value: 'matrix'. Located at position 1 within expression: matrix.path

I saw it's possible to add a parameter in the reusable workflow, and run the job only if this condition is met: https://stackoverflow.com/a/73953210

However, I prefer not to add a parameter for it. Is there a different solution?

user2653179
  • 393
  • 1
  • 6
  • 21
  • 1
    Taking a look at the [documentation](https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability), `matrix` context is indeed not available at the `jobs..if` level. Therefore you won't be able to do it here. However, you could add this condition inside your reusable workflow. It would always run, but would only perform the operation you wish when the path is the one informed on the condition. – GuiFalourd Jun 30 '23 at 11:55

1 Answers1

0

A possible solution is just to filter the list of dictionaries in generate_matrix.py:

li = [
        {
            "foo": "foo1",
            "bar": "bar1",
            "path": "path1"
        },
        {
            "foo": "foo2",
            "bar": "bar2",
            "path": "path2"
        }
    ]

final_list = [elem for elem in li if elem["path"] == "path1"]

with open("output.json", 'w') as wf:
    json.dump({"include": final_list}, wf)

user2653179
  • 393
  • 1
  • 6
  • 21