GitlabIntermediate

GitLab CI/CD Pipeline Mastery: A Comprehensive Guide

Tech Writer
11 min read

TL;DR

Continuous Integration and Continuous Deployment (CI/CD) is at the heart of modern DevOps practices, and GitLab provides one of the most powerful pipeline systems available

GitLab CI/CD Pipeline Mastery: A Comprehensive Guide

Executive Summary

A GitLab pipeline is a contract: given this commit, run these checks in this order, produce this artifact, and deploy it only if the agreed conditions hold. Mastery is not knowing every keyword in the reference. It is designing pipelines that are fast enough that developers trust them, strict enough that a green pipeline means something, and structured so the same artifact is promoted from test to production without being rebuilt. This guide covers the core model of stages, jobs, artifacts, cache, and rules, then the techniques that separate a working pipeline from a good one: needs-based DAG execution, parallelisation and matrices, child and generated pipelines, environments with protected deployments, and the failure patterns that make pipelines slow or unreliable.

Why This Matters

The pipeline is the most frequently executed piece of engineering infrastructure in most teams, and its quality compounds. A slow pipeline taxes every change and trains developers to batch work into larger, riskier merges. A flaky pipeline teaches the team to retry instead of investigate, until a real failure is retried away and ships. A pipeline that rebuilds the artifact at deploy time proves nothing about what was tested. Conversely, a fast, deterministic pipeline shortens feedback to minutes, makes small changes safe, and turns deployment into a routine event instead of a ceremony. Every optimisation and control in this guide is in service of those outcomes, not of YAML elegance.

Core Concepts

The Basic Model: Stages, Jobs, Artifacts

Pipelines are defined in .gitlab-ci.yml at the repository root. Jobs belong to stages, stages run in order, and jobs in the same stage run in parallel subject to runner capacity. Artifacts pass files from one job to later jobs; cache passes reusable files between pipelines.

stages:
  - build
  - test
  - deploy

variables:
  APP_VERSION: "1.0.0"
  DOCKER_REGISTRY: "registry.example.com"

build_job:
  stage: build
  script:
    - echo "Building application..."
    - npm install
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 week

test_job:
  stage: test
  script:
    - echo "Running tests..."
    - npm run test
  coverage: '/Coverage: \d+.\d+%/'

deploy_job:
  stage: deploy
  script:
    - echo "Deploying application..."
    - docker build -t $DOCKER_REGISTRY/myapp:$APP_VERSION .
    - docker push $DOCKER_REGISTRY/myapp:$APP_VERSION
  only:
    - main

Prefer rules over the older only and except syntax in new pipelines. Rules are evaluated in order, support variables and change detection, and are the mechanism GitLab continues to extend. Set artifact expiry deliberately: artifacts are for handover inside the pipeline and short-term evidence, not long-term storage, and unexpired artifacts across thousands of pipelines become a storage problem.

Rules, Workflow, and When Jobs Run

Two levels of control decide execution. Workflow rules decide whether a pipeline is created at all for a given source, such as a push, a merge request, a tag, or a schedule. Job rules decide whether an individual job joins a created pipeline and whether it runs automatically, manually, or delayed. The most common design error is pipelines running twice for the same change, once for the branch push and once for the merge request. Fix it at the workflow level by choosing merge request pipelines as the standard and suppressing branch pipelines when a merge request is open. Use changes-based rules to skip jobs whose inputs did not change, such as documentation-only changes skipping the full test matrix, but keep a periodic full pipeline on a schedule so skipped coverage still runs regularly.

DAG Execution with needs

Stages are a blunt ordering tool: every job in a stage waits for the whole previous stage. The needs keyword replaces that with explicit dependencies, so a job starts as soon as the specific jobs it depends on finish.

deploy:
  needs:
    - job: build
      artifacts: true

Used well, needs turns a staircase into a graph and is the single largest structural saving in many pipelines. Used carelessly, it creates jobs that start before the checks you assumed had run. Be explicit: a deploy job should need the artifact job and, through the graph, the test jobs that gate it, not merely the build.

Parallelism and Matrices

Independent work should run concurrently, and repeated work should be declared once. Parallel splits a job across runners by index; the matrix form generates a job per combination of variables, which suits test suites across versions, platforms, or scanners.

test:
  parallel: 3
  script:
    - npm run test -- --split=$CI_NODE_INDEX/$CI_NODE_TOTAL

security_checks:
  stage: security
  parallel:
    matrix:
      - SCANNER: [sast, dast, dependency-scanning]
  script:
    - gitlab-security-scan $SCANNER

Parallelism is bounded by runner capacity and by the work itself. Splitting a test suite that shares one database or one external service can make it slower and flakier. Shard stateless work aggressively and serialise work that contends on shared state.

Cache Is Not Artifacts

Cache stores files between pipelines, keyed typically on the lockfile or branch, to avoid re-downloading dependencies. Artifacts store files between jobs and are the record of what a job produced.

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/
  policy: pull-push

Key the cache on the dependency lockfile so a dependency change invalidates it, keep caches per branch or per ref to avoid cross-contamination, and never rely on cache for correctness: a job must succeed from a cold cache, just more slowly. If a build breaks when the cache is cleared, the build was depending on state it did not declare.

Environments, Review Apps, and Protected Deployments

An environment declaration connects a deploy job to a named target with a URL, giving you deployment history, rollback entry points, and a place to apply protection rules.

.deploy_template: &deploy_definition
  script:
    - kubectl apply -f k8s/
  variables:
    ENVIRONMENT: staging

deploy_staging:
  <<: *deploy_definition
  environment:
    name: staging
    url: https://staging.example.com

deploy_production:
  <<: *deploy_definition
  variables:
    ENVIRONMENT: production
  environment:
    name: production
    url: https://production.example.com
  when: manual
  only:
    - tags

Review apps extend the same idea to merge requests, creating an ephemeral environment per change with an automatic stop job when the merge request closes.

review_app:
  environment:
    name: review/$CI_COMMIT_REF_NAME
    url: https://$CI_ENVIRONMENT_SLUG.example.com
    on_stop: stop_review_app
  script:
    - deploy_review_app.sh

Protect production at the environment level: restrict who can run the deploy job, require approvals where your tier supports them, and keep the production job manual until rollback is fast and rehearsed.

Child, Multi-Project, and Generated Pipelines

Large repositories outgrow a single file. Include splits configuration into reusable local or shared files. Child pipelines move a subtree of jobs into its own pipeline triggered by a parent, which suits monorepos where each component has its own stages. Generated pipelines go one step further: a job produces a pipeline definition as an artifact and a trigger job runs it.

generate_jobs:
  stage: .pre
  script:
    - python generate_pipeline.py
  artifacts:
    paths:
      - generated-config.yml

include:
  - local: 'generated-config.yml'

Generation is powerful and dangerous in equal measure: the pipeline that runs is not the pipeline in the repository, so store the generated file as an artifact on every run, and keep the generator itself under the same review discipline as the configuration it emits.

A Complete Working Shape

A full-stack pipeline shows the pieces together: cached install, lint and tests in parallel, one build artifact, and deployment of that artifact.

image: node:16

stages:
  - install
  - lint
  - test
  - build
  - deploy

cache:
  paths:
    - node_modules/

install_dependencies:
  stage: install
  script:
    - npm ci
  artifacts:
    paths:
      - node_modules/

lint_code:
  stage: lint
  script:
    - npm run lint
    - npm run prettier:check

unit_tests:
  stage: test
  script:
    - npm run test:unit
  coverage: '/All files[^|]*\|[^|]*\s+([\d\.]+)/'

integration_tests:
  stage: test
  services:
    - mongo:4.4
  variables:
    MONGODB_URI: "mongodb://mongo:27017/test"
  script:
    - npm run test:integration

build_frontend:
  stage: build
  script:
    - npm run build
  artifacts:
    paths:
      - dist/

deploy_to_aws:
  stage: deploy
  image:
    name: amazon/aws-cli
    entrypoint: [""]
  script:
    - aws s3 sync dist/ s3://$S3_BUCKET/
    - aws cloudfront create-invalidation --distribution-id $CF_DISTRIBUTION --paths "/*"
  only:
    - main

For containerised services the same shape holds, with the image as the artifact: build and push once under the commit SHA, scan that image, then promote it.

variables:
  DOCKER_REGISTRY: "${CI_REGISTRY}/${CI_PROJECT_PATH}"
  DOCKER_TAG: "${CI_COMMIT_SHA}"

stages:
  - test
  - build
  - security
  - deploy

test:
  image: python:3.9
  stage: test
  script:
    - pip install -r requirements.txt
    - pytest --cov=app tests/
  coverage: '/TOTAL.+ ([0-9]{1,3}%)/'

build:
  stage: build
  script:
    - docker build -t ${DOCKER_REGISTRY}:${DOCKER_TAG} .
    - docker push ${DOCKER_REGISTRY}:${DOCKER_TAG}

security_scan:
  stage: security
  image: aquasec/trivy
  script:
    - trivy image ${DOCKER_REGISTRY}:${DOCKER_TAG}

deploy_k8s:
  stage: deploy
  image: bitnami/kubectl
  script:
    - kubectl set image deployment/myapp container=${DOCKER_REGISTRY}:${DOCKER_TAG}
  environment:
    name: production
    url: https://api.example.com

Troubleshooting the Failures That Matter

Timeouts should be set per job based on observed duration, not raised reflexively when a job gets slower; a job that suddenly needs three hours is telling you something.

long_running_job:
  script:
    - ./long-script.sh
  timeout: 3 hours

The recurring failure classes are: duplicate pipelines from missing workflow rules, cache poisoning from an unkeyed or over-shared cache, jobs waiting on stages that a needs graph would bypass, and secrets leaking into logs because a variable was not masked. Diagnose in that order before reaching for more runner capacity.

Decision Framework

SituationRecommendation
Pipeline runs for both branch push and merge requestFix with workflow rules; standardise on merge request pipelines
Total duration dominated by one long stageConvert stage ordering to a needs graph for the critical path
Test suite is the bottleneck and tests are independentShard with parallel or a matrix, keyed so shards are balanced
Same job definition repeated across projectsExtract to an included file or a CI/CD component and version it
Monorepo with independent componentsChild pipelines per component, triggered by changes rules
Production deploys feel riskyPin deployment to the tested artifact, protect the environment, keep the job manual until rollback is rehearsed
Pipeline is fast but failures are ignoredRemove automatic retries for test jobs and treat flakiness as a defect with an owner

Implementation Checklist

  • [ ] Workflow rules prevent duplicate branch and merge request pipelines
  • [ ] Rules, not only or except, control job execution in new configuration
  • [ ] The critical path uses needs instead of waiting on whole stages
  • [ ] Cache is keyed on the lockfile and every job passes from a cold cache
  • [ ] Artifacts have explicit expiry and contain only what later jobs need
  • [ ] One artifact is built once and promoted; deployment never rebuilds
  • [ ] Production is a protected environment with a named, rehearsed rollback
  • [ ] Secrets are masked and protected variables, and never echoed in scripts
  • [ ] Pipeline duration and failure rate are reviewed regularly, with the slowest jobs named
  • Trade-offs

    Every optimisation trades something. Aggressive parallelism shortens wall-clock time and increases runner cost and contention on shared services. Changes-based skipping saves minutes and risks an untested interaction, which is why a scheduled full run must backstop it. Generated and child pipelines scale configuration and make the executed pipeline harder to inspect. Strict gates protect production and frustrate developers when the gate is flaky, so gate quality is a prerequisite for gate strictness. There is no free performance: you pay in capacity, in complexity, or in risk, and the design task is choosing which.

    When Not to Use

    Do not put a job in the pipeline just because it can run there. Long-running data migrations, exploratory load tests, and one-off operational tasks belong in scheduled or manually triggered pipelines with their own controls, not in the merge path every developer waits on. Do not use GitLab CI as a general cron system for business processes unrelated to the repository; a scheduler or the platform's job system will serve you better. And if a check cannot be made deterministic, do not make it a merge gate: quarantine it, report on it, and fix it, rather than training the team to retry red pipelines.

    Conclusion

    A mastered pipeline is boring in the best sense: it starts once, runs the right jobs in the right order, promotes one tested artifact, and fails only when something is genuinely wrong. Build toward that with workflow rules, a needs graph, honest caching, and protected environments. Measure duration and failure rate, and keep removing the friction developers actually feel.

    References

  • GitLab CI/CD Documentation
  • GitLab Pipeline Schedules Documentation
  • GitLab Runner Documentation
  • GitLab Environments and Deployments
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.