Feedback

Chat Icon

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Conditional Jobs and Pipelines
52%

Conditional Execution Based on Predefined Variables

We are going to start with simple examples using the if clause then move to more advanced use cases.

The if clause allows you to run a job only when a condition is met. These conditions are usually based on predefined variables or custom variables you define in your .gitlab-ci.yml, project, group, or instance settings.

Example:

You want to run a job only when the branch name is main:

build_job:
  stage: build
  script:
    - echo "running build_job"
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

Example:

You want to run a job only when the branch name starts with feature/:

build_job:
  stage: build
  script:
    - echo "running build_job"
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^feature\//'

ℹ️ GitLab uses Google RE2 syntax for regular expressions.

Example:

You want to run a job only when the branch name is not main:

build_job:
  stage: build
  script:
    - echo "running build_job"
  rules:
    - if: '$CI_COMMIT_BRANCH != "main"'

Example:

You want to run a job only when the branch name is main and the commit message contains the word deploy:

build_job:
  stage: build
  script:
    - echo "running build_job"
  rules:
    - if: '$CI_COMMIT_BRANCH == 

Cloud Native CI/CD with GitLab

From Commit to Production Ready

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