Conditional Jobs and Pipelines
More Granular Conditions for Complex Pipelines
When you add a condition to a job using the if clause, it will always run if the condition is met. However, you want to control when the job should run based on the status of the previous jobs or other conditions in addition to the condition defined in the if clause. In this case, you can use the when keyword in combination with the if clause.
Example:
You want to run a job only when the target branch of the merge request is protected and no previous jobs have failed:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_PROTECTED == "true"'
when: on_success
For this specific example, since the default when is always on_success, you can omit it and we will have the same behavior:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_PROTECTED == "true"'
Example:
You want to run a job only when the user who triggered the pipeline has an email that ends with @company.local and at least one of the previous jobs has failed:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$GITLAB_USER_EMAIL =~ /@company.local/'
when: on_failure
Example:
You want to run a job only when the target branch of the merge request is protected independently of the previous job status:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_PROTECTED == "true"'
when: always
Example:
You want to run a job only when the target branch of the merge request is protected and the job was triggered manually:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_PROTECTED == "true"'
when: manual
Example:
You want to run a job only when the branch name is main and you want to run it after 1 hour:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
when: delayed
start_in: 1 hour
Example:
You want to run a job only when the branch name is main but run it every day at midnight:
build_job:
stage: build
script:
- echo "running build_job"
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
when: scheduled
cron: "0Cloud Native CI/CD with GitLab
From Commit to Production ReadyEnroll now to unlock all content and receive all future updates for free.
