Skip to content
Latchkey

How to Run a Job Only on main in GitLab CI

Gate a job on $CI_DEFAULT_BRANCH (or main) with rules: so deploys and releases only run from your trusted branch.

Use a rules: entry that matches $CI_COMMIT_BRANCH == "main". The job is added to the pipeline only when that branch is the source, and is excluded otherwise.

Match the main branch

Comparing against $CI_DEFAULT_BRANCH keeps the rule correct even if the default branch is renamed.

.gitlab-ci.yml
deploy:
  stage: deploy
  script: [./deploy.sh production]
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

Gotchas

  • In merge request pipelines, $CI_COMMIT_BRANCH is empty; use $CI_MERGE_REQUEST_TARGET_BRANCH_NAME if you need MR context.
  • A job with no matching rules: entry is silently excluded, not failed.
  • Prefer $CI_DEFAULT_BRANCH over a hardcoded "main" so a future rename does not break the rule.

Key takeaways

  • Use rules: if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH to run only on main.
  • Branch pipelines and MR pipelines expose different commit variables.
  • No matching rule excludes the job rather than failing it.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →