conditional after_script in .gitlab-ci.yml

Viewed 3227

I have written few jobs in .gitlab-ci.yml and my question is similar to this one SO Question. However, the answers provided and accepted doesn't work for my scenario.

The job has an after_script section which executes when the main task completes or fails.

Problem: I send an email alert based on whether the main task succeeded or failed, but I can't find any Gitlab CI variable that indicates the result of the job to clarify in the alert email.

How can I tell, inside the after_script section, whether the main task has succeeded or failed?"

If I use when: on_failure, then my question is when can I define my when: on_success job, since these jobs will depend on the job right before the one - so I can only execute one of these. I've been trying to find variables in Gitlab Variables for this, but couldn't find.

Also, in my after script - I can write if condition, but I am checking if someone can provide better alternate soltion

3 Answers

Problem: I send an email alert based on whether the main task succeeded or failed, but I can't find any Gitlab CI variable that indicates the result of the job to clarify in the alert email.

Also, in my after script - I can write if condition, but I am checking if someone can provide better alternate solution

May be you will be interested in new stage to provide email notification job.

Example of full .gitlab-ci.yml:

stages:
  - build
  - notify

build_job:
  stage: build
  script:
    - echo "Your awesome script"
  allow_failure: false # it's here just clarify the workflow, it's false by default

email_alarm:
  stage: notify
  when: on_failure
  script:
    - echo "Your alarm notification to email"

email_success:
  stage: notify
  when: on_success
  script:
    - echo "Your success notification to email"

So, here it is: email_alarm will be executed only if build_job has been failed. And email_success will be executed only if build_job succeed finished.

If you need to provide some artifacts from build_job to email - use gitlab artifacts in build_job and email_alarm/email_success jobs.

Or you can set your custom conditions such as:

scripts:
  - ./script_that_fails.sh > /dev/null 2>&1 || FAILED=true
  - if [ $FAILED ]
    then ./do_something.sh
    fi

Note the answer is another question - since v13.5, there's a CI_JOB_STATUS variable available in after_script.

Related