DevOps by Patrik

Understanding rules: vs only: in GitLab CI

When configuring GitLab CI/CD pipelines, two common keywords—rules: and only:—determine when a job should run. While they can seem similar, they have key differences in flexibility and functionality.

rules: – The Modern Way

rules: is the recommended and more powerful approach. It lets you control job execution using:

  • Branch names
  • File changes
  • Commit messages
  • Environment variables
  • Custom conditions (when: never, when: manual, etc.)

Example:

rules:
  - if: $CI_COMMIT_BRANCH =~ /^feature|issue\/.*$/
    changes:
      - global.json
      - src/**/*
  - if: $CI_COMMIT_BRANCH == "dev" && $CI_COMMIT_MESSAGE =~ /\[nopublish\]/
    when: never

Tipp: To detect changes to a file in the repo's root (like global.json), just add the filename without a path:

only: – The Legacy Filter

only: is simpler but limited. It matches jobs based on:

  • Branches
  • Tags
  • Pipelines from merge requests

It cannot check file changes or commit messages.

Example:

only:
  - /^feature\/.*$/
  - main
  - dev

Best Practice

Use rules: for:

  • Complex logic
  • File or folder-based triggers
  • Future-proofing pipelines

Stick with only: only for very simple setups or when updating legacy code.

gitlab
ci/cd
yaml
pipelines
devops

Comments