How to trigger a new workflow from another workflow based on a path filter?

Viewed 32

I have one workflow (that I want to be triggered by any commit with no path filter)

name: workflow1

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    ...

that triggers another workflow

name: workflow2

on:
  workflow_run:
    workflows: ["workflow1"]
    types:
      - completed

jobs:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v2
    ...

which is working fine with the workflow_run event. Now is it possible somehow to restrict workflow2 from being triggered even further (like with a path filter)? E.g. I make a commit to folder folder1 -> workflow1 triggered -> workflow2 triggered and if it's not a commit to the folder folder1, e.g. folder2 -> workflow1 triggered -> workflow2 not triggered. Is there something like the following I can add to workflow2?

name: workflow2

on:
  paths:
    - 'folder1/**'
  workflow_run:
    workflows: ["workflow1"]
    types:
      - completed

jobs:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v2
    ...

Or another way to achieve that?

Thanks in advance for any help.

1 Answers

First option: Did you consider using the action verify-changed-files in your workflow run to execute the jobs only if specific files are updated?


Second option: It's more verbose, but you could save the path from the first workflow in an artifact to download in the second workflow.

Using the variable GITHUB_EVENT_PATH that returns the path of the file with the complete webhook event payload. For example, /github/workflow/event.json

It would look like this

In the FIRST workflow, you extract the path, then you save that number into a file and upload it as an artifact.

      - name: Save the PATH in an artifact
        shell: bash
        env:
         - PATH: {{ github.event.path}} ## If it's not specific enough, you can extract the $PATH variable on a previous step using the shell.
        run: echo $PATH > path.txt

      - name: Upload the PATH
        uses: actions/upload-artifact@v2
        with:
          name: path
          path: ./path.txt

In the SECOND workflow, you get the artifact and the path from the FIRST workflow, using the following GitHub Apps:

      - name: Download workflow artifact
        uses: dawidd6/action-download-artifact@v2.11.0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          workflow: <first_workflow_name>.yml
          run_id: ${{ github.event.workflow_run.id }}

      - name: Read the path.txt file
        id: path_reader
        uses: juliangruber/read-file-action@v1.0.0
        with:
          path: ./path/path.txt

      - name: Step to check the path output from the step above with an if condition to perform an operation (or not)
        [...]

This link can also help to understand how to extract the PATH depending on the event.

Related