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

Rules and Complex Conditionals

Master advanced rules syntax with if, changes, exists, and variables for sophisticated job control logic.

Rules and Complex Conditionals

You'll learn how to use GitLab's advanced rules syntax—including if, changes, exists, and variables—to create sophisticated, precise job execution logic.

Core Concept

While basic rules let you say "run this job when X happens," complex conditionals combine multiple criteria to create highly specific execution gates. Think of it like a smart thermostat that doesn't just check temperature, but also considers time of day, occupancy, and weather forecasts before acting.

The Four Rule Keywords

if – Expression-Based Logic

Control jobs with conditional expressions using variables, refs, and pipeline metadata:

rules:
  - if: '$CI_COMMIT_BRANCH == "main" && $CI_PIPELINE_SOURCE == "push"'

changes – File-Based Triggers

Run jobs only when specific files or paths are modified:

rules:
  - changes:
      - src/**/*.js
      - package.json

exists – File Presence Detection

Execute based on whether files exist in the repository:

rules:
  - exists:
      - Dockerfile
      - docker-compose.yml

variables – Dynamic Variable Setting

Set or override variables conditionally:

rules:
  - if: '$CI_COMMIT_TAG'
    variables:
      DEPLOY_ENV: "production"

Combining Conditions

The real power emerges when you chain multiple rule clauses—GitLab evaluates them top-to-bottom, stopping at the first match:

deploy_job:
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      changes:
        - deploy/**/*
      when: manual
    - if: '$CI_COMMIT_TAG'
      when: always

This job runs manually when deploy files change on main, but automatically for tags.

Key Takeaway: Complex conditionals with if, changes, exists, and variables transform simple pipelines into intelligent automation that responds precisely to code changes, branch context, and repository state.