简体   繁体   中英

Trigger action/job if pipeline job/stage fails

I have a GitLab pipeline one of whose jobs writes some content into a file, a simple .txt file, and pushes a Git tag. After this job, other jobs are executed.

I want to trigger an automatic action/job or something that undoes the .txt file writing and deletes the Git tag in case any of the jobs of the pipeline fails.

Is it possible to do such a thing? Is there some kind of GitLab pipeline job that triggers only in case another fails?

You're looking for the when: on_failure option. The docs for it are here: https://docs.gitlab.com/ee/ci/yaml/README.html#when

If you put this on a job, that job will only run if another job in your pipeline from an earlier stage fails. If you only need one at the end of your pipeline, this will work fine, but it also lets you use multiple after each stage that needs it. Here's an example from the docs:

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

The job in the build stage runs whatever's necessary to build the project, but if anything fails, the job in the cleanup_build stage will run and remove any build artifacts, or whatever else is needed.

If the build job passes, the test stage job runs the tests. If these pass, we don't have to do any cleanup so the pipeline would just fail immediately. Otherwise, we continue to the deploy stage.

Our deploy stage job is marked with when: manual which is another useful option for your pipelines. It means that this job will not run until either a Gitlab user or API hits a button to start the job.

Our last job in the cleanup stage has when: always . This means that no matter what happens in any previous stage, it will always run. This is great for a final cleanup, and if a deployment fails we could perform a rollback or anything else we might need.

The docs for the when keyword and all its options are here: https://docs.gitlab.com/ee/ci/yaml/README.html#when

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM