Multiple on_failure events for each job in gitlab?

Viewed 987

Gitlab ci offers 'when: on_failure' error handler. What if I want to have a different handler for each job? Because on failure is triggered if any preceeding job has failed. So that's basically if I set that handler for each job if one job will fail then all handlers will be launched. How to avoid that?

2 Answers

I don't believe there's any way to do this currently, but there is an open issue on the gitlab repo asking for some similar functionality: https://gitlab.com/gitlab-org/gitlab/issues/19400. If implemented, it would let you specify which step should run for which failed step.

Until then though, the only way you could control the error handling is to do it in the step script like this:

./script_that_fails.sh || FAILED=true
if [ $FAILED ]; then
  ./error_handling_script.sh
fi

I just succeed to handle only one failure job for a specific job failure.

It's a little tricky, I create an artifact on failure, in the on_failure job I try to call the artifact and execute a script to handle the failure. If the artifact doesn't exist then I echo a simple message. I found this workaround in the last 10 minutes so could be optimise but it do the job.

With that you can have specific on_failure job to handle the failure of different jobs.

stages:
  - stage1
  - stage1:failure
  - stage2
  - stage2:failure

job1:
  stage: stage1
  script:
    - echo "FAIL" > JOB1
    - ...fail something
  artifacts:
    when: on_failure
    paths:
      - JOB1

job1:failure:
  stage: stage2:failure
  script:
    - cat JOB1 && some_script_to_handle_failure || echo "Not a JOB1 Failure"
  when: on_failure

job2:
  stage: stage2
  script:
    - echo "FAIL" > JOB2
    # Won't be execute since job1 fail
  artifacts:
    when: on_failure
    paths:
      - JOB2

job2:failure:
  stage: stage2:failure
  script:
    - cat JOB2 && some_script_to_handle_failure || echo "Not a JOB2 Failure"
    # Will echo "Not a JOB2 Failure" since JOB2 artifact doesn't exist.
  when: on_failure

Hope it will help.

Related