Is there any way to trigger a Github action if the previous one failed but the current one succeded?

Viewed 1292

I have set up a Github action to send an email on failure (for integration tests) and I'd like to send another one to notify that it recovered; for that I need to know if the previous run failed but the current one succeeded.

This is the code for the failure:

(...)
- name: Send mail if failed
  if: ${{ failure() }}
  uses: juanformoso/action-send-mail@1
  with:
(...)

Is there a way to accomplish what I need? something like ${{ if success_but_previous_failed() }}?

EDIT: I mean between workflow "runs", this is the situation I want to detect:

enter image description here

The last run should send a "tests recovered" mail

2 Answers

Expanding on soltex's excellent answer, I ended up doing this in order to make an authenticated API call:

- name: Get latest workflow run status
  uses: actions/github-script@v3
  id: latest-workflow-status
  with:
    script: |
      const runs = await github.actions.listWorkflowRuns({
        owner: context.repo.owner,
        repo: context.repo.repo,
        workflow_id: 'runtests.yml',
        per_page: 2
      })
      return runs.data.workflow_runs[1].conclusion
    result-encoding: string
(...)
- name: Send mail if previous workflow run failed and the current succeeded
  if: ${{ success() && steps.latest-workflow-status.outputs.result == 'failure' }}
(...)
- name: Send mail if previous workflow run succeeded and the current failed
  if: ${{ failure() && steps.latest-workflow-status.outputs.result == 'success' }}
(...)

You can use GitHub Actions API and make a request to:

GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs

in order to get all runs of a specific workflow and then parse the output to retrieve the latest run result.

I will use this public repository to show you an example:

  - name: Get latest workflow run status
    id: latest-workflow-status
    run: echo "::set-output name=result::$(curl https://api.github.com/repos/sdras/awesome-actions/actions/workflows/32764/runs 2>/dev/null | jq -r '.workflow_runs[0].conclusion')"

  - name: Run only if previous workflow run failed and the current succeeded
    if: ${{ success() && steps.latest-workflow-status.outputs.result == 'failure' }}
    run: ...

You can get the workflow ids from this request:

https://api.github.com/repos/sdras/awesome-actions/actions/workflows

Related