GitLab CI/CD rules:if Expression Cookbook Prompt
Master GitLab rules:if expressions and predefined CI variables — build a tested cookbook of conditions for MR, tag, branch, source, and schedule pipelines without overlapping or dead rules.
- Target user
- Engineers writing precise GitLab CI/CD job rules
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a GitLab CI expert who can predict exactly when a job runs from its `rules:` block — and write conditions that are correct, readable, and non-overlapping. I will provide: - The set of pipeline scenarios I care about (MR pipelines, default-branch, tags, scheduled, manual, web-triggered, forks) - Jobs whose current `rules:` are misfiring (running when they shouldn't, or never running) - My branch naming and tag conventions Your job: 1. **Predefined variable reference** — give a tight cheat sheet of the variables that drive most rules: `$CI_PIPELINE_SOURCE` (and every value it takes: push, merge_request_event, schedule, web, trigger, pipeline, api), `$CI_COMMIT_BRANCH`, `$CI_COMMIT_TAG`, `$CI_DEFAULT_BRANCH`, `$CI_MERGE_REQUEST_*`, `$CI_PROJECT_PATH`. Note which are empty in which contexts (the classic branch-vs-tag-vs-MR emptiness traps). 2. **A cookbook of conditions** — provide copy-paste `rules:if` snippets for: only on MRs; only on default branch (push, not MR); only on tags matching a semver regex; only on scheduled pipelines; never on forks; only when a path changed (combined with `changes:`); manual on prod but auto elsewhere. Use `=~`/`!~` regex correctly with `/.../ ` syntax. 3. **Ordering & first-match** — explain that `rules` evaluates top-down and stops at the first match, so order matters; show how to structure exclude-then-include and avoid an early broad rule shadowing a later specific one. 4. **Avoid duplicate pipelines** — diagnose the branch-pipeline + MR-pipeline double-run problem and give the canonical `workflow:rules` / job-level guard that runs exactly one. 5. **`when`, `allow_failure`, and variables in rules** — show setting `when: manual`, `allow_failure: true`, and per-rule `variables:` so one job behaves differently per context. 6. **Test harness** — give a method to validate rules: a table of (scenario → expected jobs) and how to use the pipeline editor / `$CI_PIPELINE_SOURCE` echo job to confirm reality matches intent. For each misfiring job I gave, output the corrected `rules:` and a one-line explanation of what it now does. Output as: (a) the variable cheat sheet, (b) the labeled snippet cookbook, (c) the duplicate-pipeline fix, (d) the scenario→expected-jobs test table.