Course contentsShow
← Cloud and Infrastructure
Lesson 1737 of 2,98936. GitLab CI/CDFree lesson

Job Rules: Basic Conditional Execution

Apply simple rules to control when jobs run based on branches, tags, or pipeline type.

Job Rules: Basic Conditional Execution

What you'll learn: How to use rules to control whether a job runs based on branch names, tags, or pipeline types.

The Core Idea

Not every job needs to run in every pipeline. You might want tests to run on every branch, but deployments only on main. Or perhaps certain jobs should only trigger for merge requests, not regular commits. GitLab's rules keyword lets you define conditions that determine whether a job executes.

Think of rules as a bouncer at a club checking IDs—each rule evaluates the pipeline context (branch name, tag, pipeline type) and decides if the job gets in.

Basic Rules Syntax

Rules are evaluated top-to-bottom. The first matching rule determines the job's fate:

deploy_production:
  script:
    - echo "Deploying to production"
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: always
    - when: never

This job only runs when the commit is on the main branch. All other scenarios are blocked by when: never.

Common Rule Patterns

Run only on specific branches:

rules:
  - if: '$CI_COMMIT_BRANCH == "develop"'

Run only for tags:

rules:
  - if: '$CI_COMMIT_TAG'

Run only for merge request pipelines:

rules:
  - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

Exclude specific branches:

rules:
  - if: '$CI_COMMIT_BRANCH == "main"'
    when: never
  - when: always

Each if evaluates a condition using environment variables you've learned about. When a condition matches, the associated when clause (always, never, manual) controls execution.

Key Takeaway: Use rules with conditional expressions to precisely control which pipelines trigger which jobs, making your CI/CD workflows smarter and more efficient.