Conditional Job Execution with GitLab CI Rules

Master GitLab CI rules for conditional job execution. Use if conditions, changes, exists, and variables to control when jobs run in your pipeline.

Pipeline Architecture

Detailed Explanation

Conditional Rules in GitLab CI

Rules replace the older only/except keywords and provide precise control over when jobs are included in a pipeline.

Branch-Based Rules

deploy_staging:
  stage: deploy
  script: make deploy-staging
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'

deploy_production:
  stage: deploy
  script: make deploy-production
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: manual
      allow_failure: false

Tag-Based Rules

release:
  stage: deploy
  script: make release
  rules:
    - if: '$CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/'

Merge Request Rules

review:
  stage: test
  script: make lint
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

File-Based Rules

build_docs:
  stage: build
  script: make docs
  rules:
    - changes:
        - docs/**/*
        - README.md

terraform_plan:
  stage: plan
  script: terraform plan
  rules:
    - exists:
        - terraform/*.tf

Rule Evaluation Order

Rules are evaluated top to bottom. The first matching rule determines the job's behavior. If no rule matches, the job is excluded from the pipeline.

deploy:
  rules:
    # Manual deploy on main
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: manual
    # Auto deploy on develop
    - if: '$CI_COMMIT_BRANCH == "develop"'
      when: on_success
    # Skip all other branches
    - when: never

Common Pitfall

Without a final - when: never or - when: on_success catch-all, the job is excluded when no rule matches. This is different from only/except where the default was to include the job.

Use Case

Use rules for any pipeline that needs different behavior based on branches, tags, merge requests, or file changes. Essential for implementing deployment strategies and saving CI resources.

Try It — GitLab CI Config Generator

Open full tool