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

Rules and Conditional Execution

Using rules to conditionally run jobs based on branches, tags, variables, and changes.

Rules and Conditional Execution

What you'll learn: How to use rules in GitLab CI/CD to decide when jobs should run based on branches, tags, variables, and file changes.

The Core Idea

Not every job should run in every pipeline. You might want tests to run on all branches, but deployments only on main. Or perhaps you want a job to run only when specific files change, or when certain variables are set. GitLab's rules keyword gives you fine-grained control over job execution by evaluating conditions before the job starts.

Think of rules like a bouncer at a club entrance: each rule checks credentials (branch name, variables, file changes) and decides whether the job gets in or stays out.

How Rules Work

Rules are evaluated top-to-bottom. The first matching rule determines the job's behavior. Each rule can specify:

  • if: Evaluate an expression (checking variables, branch names, commit messages)
  • changes: Run only if specific files were modified
  • exists: Run if certain files exist in the repository
  • when: Control timing (on_success, manual, always, never)
deploy_production:
  script:
    - echo "Deploying to production"
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: on_success
    - when: never

test_changes:
  script:
    - npm test
  rules:
    - changes:
        - src/**/*.js
        - tests/**/*.js

The deploy_production job runs only on the main branch. The test_changes job runs only when JavaScript files in src/ or tests/ are modified. If no rule matches, the job won't run (unless you add a catch-all).

Key Takeaway: Use rules to conditionally execute jobs based on branch names, tags, variables, and file changes, ensuring pipelines run efficiently and only when needed.