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

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)"

Instead of determining whether or not the task succeeded or failed in the after_script, I would suggest defining another stage, and using the when syntax, where you can use when: on_failure or when: on_success.


Example from the documentation:

stages:
- build
- cleanup_build
- test
- deploy
- cleanup

build_job:
  stage: build
  script:
  - make build

cleanup_build_job:
  stage: cleanup_build
  script:
  - cleanup build when failed
  when: on_failure

test_job:
  stage: test
  script:
  - make test

deploy_job:
  stage: deploy
  script:
  - make deploy
  when: manual

cleanup_job:
  stage: cleanup
  script:
  - cleanup after jobs
  when: always