Feedback

Chat Icon

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Conditional Jobs and Pipelines
60%

Conditional Execution Based on Job Status

The when keyword allows you to define when a job should run. Let's try different values for the when keyword and see how they work.

stages:
  - stage-0
  - stage-1
  - stage-2
  - stage-3
  - stage-4
  - stage-5
  - stage-6
  - stage-7

job-0:
  stage: stage-0
  script:
    - echo "running job-0"

job-1:
  stage: stage-1
  script:
    - echo "running job-1"
  when: on_success

job-2:
  stage: stage-2
  script:
    # This job will fail
    - echo "running job-2"
    - exit 1

job-3:
  stage: stage-3
  script:
    - echo "running job-3"
  when: on_failure

job-4:
  stage: stage-4
  script:
    - echo "running job-4"

job-5:
  stage: stage-5
  script:
    - echo "running job-5"
  when: always

job-6:
  stage: stage-6
  script:
    - echo "running job-6"
  when: manual

job-7:
  stage: stage-7
  script:
    - echo "running job-7"
  when: delayed
  start_in: 1 minute  

Based on the configuration above, this is what will happen:

  • job-0 will run successfully.

  • job-1 will run only when job-0 has succeeded because of the when: on_success clause. The on_success value means that the job will run only when no jobs in earlier stages fail or have allow_failure: true. In this case, job-1 will run. It's worth noting that the on_success value is the default value for the when keyword.

  • job-2 will fail because we forced it to fail (exit 1).

  • job-3 will run only when only when at least one of the previous jobs has failed because of the when: on_failure clause. In this case, job-3 will run.

  • job-4 will not run because the previous job has failed (by default, the when keyword is set to on_success).

  • job-5 will run regardless of the status of jobs in earlier stages because of the when: always clause.

  • job-6 will run only when triggered manually because of the when: manual clause. It will not run automatically. The only way to run it is to trigger it manually using the GitLab UI.

  • job-7 would run after 1 minute because of the when: delayed clause. However, since there are earlier jobs that have failed, it will not run at all.

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Enroll now to unlock all content and receive all future updates for free.