Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop GitHub Jobs in Progress if Another Failed (stop on fail)

TL; DR: Running jobs a,b in parallel. If a fails, stop the execution of b, while it's still running.

My company uses GitHub Actions to deploy our code.

The first step in our deployment is building dockers and pushing them to DockerHub.

We wrote a test for our code, which we want to run in parallel with building the dockers.

Both of these are separate jobs, and we have a few more jobs depending on the success of the first two.

Right now, if the test job fails, the other job continues to run, but obviously, the next one won't run, because the test job failed.

What I would like to do is cancel the docker building job while it's running, if the test failed.

Is that possible? After searching the web, StackOverflow and the GitHub Actions page, I haven't found a way to do that.

Thanks!

like image 364
Gil Cohen Avatar asked Mar 15 '26 12:03

Gil Cohen


2 Answers

Since you are working on an enterprise project, I would prefer to avoid using unverified actions from public repositories no matter how many stars they have. I think you can add a step to the end of each job a, b. This step will only run if previous steps failed. If it is failed then it will send a cancel-workflow api call.

- if: failure()
  name: Check Job Status
  uses: actions/github-script@v6
  env: 
     RUN_ID: ${{ github.run_id }}
     GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  with:
     script: |
       const runId = process.env.RUN_ID
       const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
       const resp = await github.rest.actions.cancelWorkflowRun({
         owner,
         repo,
         runId
       }) 

Note: You may need to add another custom github_pat since this api-call may require higher permissions than default actions. I also suggest you to take a look at this post , I found it quite useful.

like image 180
orhunozbal Avatar answered Mar 17 '26 02:03

orhunozbal


You can use the Cancel this build action.

The basic idea is to add it as a final step in each of your jobs that you want to cause a short-circuit in case of failure:

jobs
  job_a:
    steps:
      - run: |
          echo 'I am failing'
          exit 1
      - name: Cancelling parallel jobs
        if: failure()
        uses: andymckay/[email protected]
  job_b:
    steps:
      - run: echo 'long task'

This will basically cancel job_b or any other in the same workflow whenever job_a fails.

like image 20
robertohuertasm Avatar answered Mar 17 '26 02:03

robertohuertasm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!