Search code examples
githubconditional-statementsgithub-actions

Conditional job execution for Github actions


I would like to conditionally execute a Github Action according to a previous job (Format). If the code needed to be formatted, I would like to execute the following job (create_commit), otherwise skip it and do nothing.

Unfortunately at the moment the second job never gets triggered, no matter what is the output of the first job.

My action:

name: Format
on: push
jobs:
  format:
    name: Code formatting in Black
    runs-on: ubuntu-latest
    outputs:
      trigger_commit: ${{ steps.changes_present.outputs.changes_detected }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
      - name: Install package
        run: pip install 'black[d]'
      - name: Run black formatter
        run: black .
      - name: Check diff for changes
        id: changes_present
        run: |
            outputs=$(git diff)
            if ! [ -z "$outputs" ]
            then
              echo '::set-output name=changes_detected::true' 
            fi
  create_commit:
    runs-on: ubuntu-latest   <- Job never executed
    needs: format
    if: needs.format.outputs.changes_detected == true        
    steps:
      - name: Commit
        run: |
          git config user.name 'github-actions[bot]'
          git config user.email 'github-actions[bot]@users.noreply.github.com'
          git commit -am "Files updated after formatting"
          git push

Solution

  • The output of the format job is named trigger_commit instead of changes_detected. So try this:

     if: needs.format.outputs.trigger_commit == `true`        
    

    You could use the actionlint to check this error, an online version is available too. See this link .