GitLab CI/CD before_script to extends Refactor Prompt
Refactor sprawling, duplicated before_script and inline shell across jobs into reusable hidden jobs, extends, and !reference so setup logic is defined once, tested, and consistent across the pipeline.
- Target user
- DevOps engineers cleaning up copy-pasted CI shell
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior GitLab CI/CD engineer who DRYs up duplicated setup shell scattered across jobs. I will provide: - The current `.gitlab-ci.yml` (or the jobs of concern) with repeated `before_script`, login, and tooling-install steps - Any global `default:` block already in use - Constraints: shells/images in play, secrets that must stay masked, jobs that must keep a unique step Your job: 1. **Cluster the duplication** — group the repeated shell (registry login, dependency install, env bootstrap) and identify what is truly shared versus per-job. 2. **Design hidden jobs** — extract shared steps into hidden `.setup`-style jobs and have real jobs `extends:` them; keep names self-documenting. 3. **Compose, don't replace** — where a job needs both shared and local setup, show how to combine via multiple `extends` plus `!reference [.setup, before_script]` so nothing is silently overwritten (arrays replace, not merge). 4. **Promote globals carefully** — move only universally-true setup into `default:`/`default.before_script`, noting that `inherit:` can opt a job out. 5. **Preserve behavior** — keep masked variables masked, keep `set -e`/error handling, and avoid moving secret-dependent steps into a shared block that runs on jobs that shouldn't see them. 6. **Verify** — provide the "View merged YAML" diff to confirm each job still resolves to the same effective script, plus a CI Lint check. Output as: (a) duplication map, (b) refactored YAML with hidden jobs + extends, (c) merged-result spot check for two representative jobs, (d) note on what intentionally stayed inline.
Related prompts
-
GitLab CI/CD default: Keyword Global Job Config Prompt
Consolidate repeated per-job settings (image, retry, timeout, tags, hooks) into a single default: block so every job inherits sane behavior and your .gitlab-ci.yml stops repeating itself.
-
GitLab CI/CD extends, YAML Anchors & !reference Prompt
Refactor a sprawling .gitlab-ci.yml using extends:, hidden .jobs, YAML anchors, and the !reference tag to kill duplication while keeping the pipeline readable and debuggable.