.gitlab-ci.yml after_script section: how can I tell whether the task succeeded or failed?

Daniel Griscom picture Daniel Griscom · Apr 17, 2018 · Viewed 9.2k times · Source

I'm using Gitlab CI, and so have been working on a fairly complex .gitlab-ci.yml file. The file has an after_script section which runs when the main task is complete, or the main task has failed somehow. Problem: I need to do different cleanup based on whether the main task succeeded or failed, but I can't find any Gitlab CI variable that indicates the result of the main task.

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

Answer

Carl Bélanger picture Carl Bélanger · Mar 26, 2019

The accepted answer may apply to most situations, but it doesn't answer the original question and will only work if you only have one job per stage.

Note: There currently a feature request opened (issues/3116) to handle on_failure and on_success in after_script.

It could be possible to use variables to pass the job status to an after_script script, but this also has a feature request (issues/1926) opened to be able to share variables between before_script, script and after_script.

One workaround will be to write to a temporary file that will be accessed during the after_script block.

test_job:
  stage: test
  before_script:
    - echo "FAIL" > .job_status
  script:
    - exit 1
    - echo "SUCCESS" > .job_status
  after_script:
    - echo "$(cat .job_status)"