Include and Extends
What you'll learn: How to eliminate repetition in GitLab CI/CD pipelines by reusing configuration from external files and job templates.
As your GitLab pipelines grow, you'll find yourself copying the same job configurations across projects or repeating similar job definitions within a single .gitlab-ci.yml file. GitLab provides two powerful mechanisms to keep your pipeline configuration DRY (Don't Repeat Yourself): include for pulling in external files and extends for inheriting from job templates.
Include: External Configuration Files
The include keyword lets you import YAML configuration from external sources—other files in your repository, different projects, or even remote URLs. This is like having a shared library of common pipeline pieces that multiple projects can reference.
include:
- local: '/templates/build-template.yml'
- project: 'my-group/pipeline-templates'
file: '/deploy-jobs.yml'
Extends: Job Templates
The extends keyword allows a job to inherit configuration from a template job (often prefixed with a dot to hide it from execution). Think of it as object inheritance—the child job gets all the parent's properties but can override or add its own.
.base_deploy:
stage: deploy
script:
- echo "Deploying application"
only:
- main
deploy_production:
extends: .base_deploy
environment: production
variables:
DEPLOY_ENV: "prod"
Here, deploy_production inherits the stage, script, and only rules from .base_deploy, while adding its own environment and variables.
Key Takeaway: Use include to share configuration across projects and files, and extends to create reusable job templates within your pipeline, dramatically reducing duplication and making pipelines easier to maintain.