Ravindra BagaleCourses & study guides मराठी

Chapter 92: GitLab CI Deep Dive

DevOps

92.12 include, extends and reusable templates

Story (fictional teaching scenario). At a fictional IT services firm in Coimbatore, twenty projects had twenty copies of the same test job. Sven from Gothenburg moved the common parts into one template file in a shared project. Each project now has a short .gitlab-ci.yml that includes the template and extends the hidden base job. A fix in the template reaches all twenty.

include pulls YAML from other files or projects. extends copies a hidden base job. Fix once, reuse everywhere.
include pulls YAML from other files or projects. extends copies a hidden base job. Fix once, reuse everywhere.

Why

Copy-paste CI drifts. Shared templates give one place to review and fix.

What

  • include:local — Pull in another YAML file from the same repo.
  • include:project — Pull in a file from another GitLab project, pinned with ref:.
  • include:template — GitLab's own built-in templates.
  • include:component — CI/CD components from the CI/CD Catalog, with inputs (see GitLab docs for current syntax).
  • Hidden job — A job name starting with a dot, like .base-test. It never runs by itself.
  • extends — Copy settings from a hidden job, then add or override.
  • !reference — Reuse one section (like a script list) from another job.

How

  1. Write a hidden base job with shared settings.
  2. Put it in a template file.
  3. include: that file.
  4. Make real jobs extends: the base and add only what differs.

Example 1: Template and caller in one repo

# ci/templates.yml
.base-test:
  image: python:3.13-slim
  before_script:
    - pip install -r requirements.txt
  artifacts:
    when: always
    reports:
      junit: report.xml
# .gitlab-ci.yml
include:
  - local: ci/templates.yml

unit-test:
  extends: .base-test
  script:
    - python -m pytest -q --junitxml=report.xml

Line by line: The template defines a hidden job. The main file includes it, then unit-test extends it and adds only its own script. The merged job has the image, setup, report settings and script.

Output (illustrative — pipeline not run)

CI Lint → Full configuration:
unit-test:
  image: python:3.13-slim
  before_script: [pip install -r requirements.txt]
  script: [python -m pytest -q --junitxml=report.xml]
  artifacts: {when: always, reports: {junit: report.xml}}

What it means: GitLab's pipeline editor can show the fully merged result, so you can check what extends produced.

Example 2: Include from another project, pinned

include:
  - project: "platform/ci-templates"
    ref: "v1.4.0"
    file: "/python/test.yml"

What it means: Every project uses version v1.4.0 of the shared template until it chooses to upgrade. Project path and tag are examples.

Ravindra Bagale's Tip

Pin shared includes to a tag, not a branch. Otherwise one bad template commit breaks every project at once.

Did you understand? Let us try it once more.