.gitlab-ci.yml after_script 部分:如何判断任务是成功还是失败?

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

我正在使用 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 指示主要任务的结果。

如何判断 after_script 部分中的主要任务是成功还是失败?

与其在 after_script 中确定任务是成功还是失败,我建议定义另一个阶段,并使用 when 语法,您可以在其中使用 when: on_failurewhen: on_success.


文档中的示例:

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

接受的答案可能适用于大多数情况,但它不能回答原始问题,并且只有在每个阶段只有一份工作时才有效。

注意:目前已打开功能请求 (issues/3116) 以处理 after_script 中的 on_failureon_success

可以使用变量将作业状态传递给 after_script 脚本,但这也打开了一个功能请求 (issues/1926) 以便能够在 [=] 之间共享变量15=]、scriptafter_script

一种解决方法是写入将在 after_script 块期间访问的临时文件。

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

从 gitlab-runner 13.5 开始,你可以使用 CI_JOB_STATUS 变量。

test_job:
  # ...
  after_script:
    - >
      if [ $CI_JOB_STATUS == 'success' ]; then
        echo 'This will only run on success'
      else
        echo 'This will only run when job failed or is cancelled'
      fi

参见 GitLab 关于 predefined_variables 的文档:https://docs.gitlab.com/ee/ci/variables/predefined_variables.html