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_BRANCHGotchas
- In merge request pipelines,
$CI_COMMIT_BRANCHis empty; use$CI_MERGE_REQUEST_TARGET_BRANCH_NAMEif you need MR context. - A job with no matching
rules:entry is silently excluded, not failed. - Prefer
$CI_DEFAULT_BRANCHover a hardcoded"main"so a future rename does not break the rule.
Key takeaways
- Use
rules: if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCHto 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
How to Use rules vs only/except in GitLab CIUse rules: in GitLab CI to control when jobs run and migrate off the deprecated only/except keywords, with br…
How to Deploy with Environments in GitLab CIDeploy with GitLab CI environments using the environment: keyword to track deployments, link to live URLs, an…