Get the state of the whole Github Actions workflow, not just a single job

Viewed 20

I'm trying to send messages to slack from a Guthub Actions workflow regarding the success/failure of the workflow.

  finally:
    runs-on: ubuntu-latest
    needs: ['ci-build', 'lint-yaml', 'lint-json', 'lint-env-files', 'lint-folders', 'lint-filenames', 'shellcheck', 'lint-dockerfile']
    if: always()

    steps:
      - name: Send pipeline status to Slack
        if: always()
        uses: kpritam/slack-job-status-action@v1
        with:
          job-status: ${{ job.status }}
          slack-bot-token: ${{ secrets.SLACK_BOT_TOKEN }}
          channel: C0438TFQNPM # pipelines channel

Sending the message works. But ${{ job.status }} does not represent the state of the whole pipeline, only the last job.

I want to send a failure, if any step in any job fails. This is my workflow run which I use for testing: https://github.com/sebastian-sommerfeld-io/docker-image-adoc-antora/actions/runs/3096876874

The workflow itself works as intended. But my slack message reports "success". It should report "failure" because one job failed and another job is subsequently skipped.

Anyone got an idea how I can get the state of the whole workflow, not just a single job in a Github Actions workflow?

1 Answers

Rather than sending a notification for each job that fails (or succeeds) it is usually possible to 'chain' the jobs together by using the needs keyword to create a dependency tree.

To keep the logic separate, you can add a final job just to perform the notification to Slack, and this can be set up as a dependency on all your earlier jobs.

The final job can calculate the overall workflow status using something like ${{ job.status == 'success' && needs.earlierjob1.result == 'success' && needs.earlierjob2.result == 'success' } to represent a boolean of overall success. This can become easier to maintain by using needs.*.result instead of listing each job by name.

I wrote an article going into more detail here, including examples of what works and what doesn't.

In the end, I built a native Slack app to take care of this automatically so you don't need to think about job status or notifications at all.

Related