Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 44 ยท Projects

Project: A GitLab Pipeline with Review Apps

Build a GitLab CI/CD pipeline with stages, includes, merge request pipelines, review environments, a manual production deploy and cleanup when a branch is gone.

A review app is a temporary copy of your application, deployed for one merge request, so that reviewers can click through the change instead of reading a diff. GitLab has first-class support for this idea through environments: a job declares an environment name and URL, GitLab lists it on the merge request, and a second job tears it down when the branch is merged or deleted.

In this project you will assemble a complete .gitlab-ci.yml for a web application: tests on every change, a review environment per merge request, automatic deployment of main to staging, and a manual button for production. The YAML is read-only, because it needs a GitLab server with runners and a place to deploy to. The runnable part is a stand-in: a small simulation of the environment lifecycle that shows what GitLab keeps track of when environments are created, updated and stopped. It builds on GitLab CI/CD Basics, Rules, needs, Artifacts and Cache and Includes, Templates and Environments.

The goal

Here is what each kind of pipeline should do:

Pipeline Runs Deploys
Merge request lint, test, build review environment review/<branch>
Default branch lint, test, build staging automatically; production on a manual click
Other branch pushes nothing (the merge request pipeline covers them) nothing
flowchart LR
  MR["Merge request<br/>pipeline"] --> R["review app<br/>review/branch-name"]
  R --> ST["stop job<br/>(merge or delete)"]
  M["main pipeline"] --> S["staging"]
  S --> P["production<br/>manual click"]

Review apps live and die with the merge request; staging and production belong to the default branch.

Step 1: workflow rules to avoid duplicate pipelines

If you open a merge request from a branch that already has a push pipeline, GitLab can start two pipelines for the same commit. The workflow:rules block decides which pipelines exist at all:

YAML
workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_COMMIT_TAG

Read it top to bottom; the first rule that matches wins. Merge request events create a pipeline. A branch push on a branch that has an open merge request is dropped (the merge request pipeline handles it). The default branch and tags get their own pipelines. A feature branch with no merge request yet gets no pipeline, which is the quiet default many teams want.

GitLab also ships a ready-made template for this. Including Workflows/MergeRequest-Pipelines.gitlab-ci.yml gives similar behavior, and you can add your own rules next to it.

Step 2: stages, defaults and includes

Keep the top of the file tidy by putting shared settings in default and splitting very large pipelines into included files:

YAML
stages: [check, build, review, staging, production]

default:
  image: node:22
  interruptible: true
  cache:
    key:
      files: [package-lock.json]
    paths: [.npm/]

variables:
  npm_config_cache: "$CI_PROJECT_DIR/.npm"

include:
  - local: ci/deploy-templates.yml
  - template: Security/SAST.gitlab-ci.yml

interruptible: true lets GitLab cancel an older running pipeline when a newer commit arrives on the same branch, if you also enable auto-cancel for redundant pipelines in the project settings. The cache key is derived from package-lock.json, so dependencies are re-downloaded only when the lock file changes. The local include pulls a file from the same repository, where we will keep reusable hidden jobs; the template include adds GitLab's own static security scanning jobs. Which templates are available depends on your GitLab edition and version, so check the list on your instance.

Step 3: check and build jobs

YAML
lint:
  stage: check
  script:
    - npm ci
    - npm run lint

test:
  stage: check
  script:
    - npm ci
    - npm test -- --coverage
  coverage: '/Lines\s*:\s*(\d+\.?\d*)%/'
  artifacts:
    when: always
    reports:
      junit: reports/junit.xml

build:
  stage: build
  script:
    - npm ci
    - npm run build
  artifacts:
    paths: [dist/]
    expire_in: 1 week

lint and test share a stage, so they run in parallel. The coverage regular expression pulls a number out of the log so GitLab can show it on the merge request. The reports: junit: artifact makes failed tests visible in the merge request widget, and when: always uploads it even if the tests failed. The dist/ folder is handed to later stages automatically because jobs in later stages download artifacts from earlier ones by default.

Step 4: reusable deploy logic with hidden jobs

Three deploy jobs will share most of their script. In the included ci/deploy-templates.yml, define a hidden job (its name starts with a dot, so GitLab never runs it by itself):

YAML
.deploy:
  image: alpine:3.20
  before_script:
    - apk add --no-cache openssh-client rsync
    - mkdir -p ~/.ssh && chmod 700 ~/.ssh
    - echo "$DEPLOY_KEY" | tr -d '\r' > ~/.ssh/id_ed25519
    - chmod 600 ~/.ssh/id_ed25519
  script:
    - ./scripts/deploy.sh "$DEPLOY_TARGET" dist/

The DEPLOY_KEY variable would be a masked and protected CI/CD variable, available only to protected branches. If you can avoid long-lived SSH keys by using your cloud's short-lived identity federation, prefer that; the pattern for jobs stays the same.

Step 5: the review app and its cleanup

This is the heart of the project. The review job creates a dynamically named environment; the stop job is linked to it with on_stop:

YAML
deploy_review:
  extends: .deploy
  stage: review
  variables:
    DEPLOY_TARGET: "$CI_ENVIRONMENT_SLUG"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: https://$CI_ENVIRONMENT_SLUG.review.example.com
    on_stop: stop_review
    auto_stop_in: 1 week
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

stop_review:
  stage: review
  image: alpine:3.20
  variables:
    GIT_STRATEGY: none
  script:
    - echo "Removing the review app for $CI_ENVIRONMENT_SLUG"
    - ssh [email protected] "rm -rf /srv/apps/$CI_ENVIRONMENT_SLUG"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    action: stop
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: manual
  allow_failure: true

Several details make this work. The environment name contains $CI_COMMIT_REF_SLUG, a lowercase, URL-safe version of the branch name, so each branch gets its own environment under the review/ folder in the GitLab UI. on_stop names the job that GitLab runs automatically when the merge request is merged or the branch is deleted, and the stop job repeats the same environment name with action: stop. GIT_STRATEGY: none skips the repository checkout in the stop job, because the branch may already be gone when it runs. The auto_stop_in setting is a safety net: if everyone forgets, the environment is stopped after a week.

The stop job does not extend .deploy on purpose. It runs without a checkout, so it cannot call a script from the repository, and it does not need the deploy tools or the deploy key set up in before_script. In this sketch it uses an inline command; a real one needs its own access to the host, supplied as a variable or an identity-based login. Keep teardown self-contained and it still works after the branch is gone.

Step 6: staging and a manual production deploy

YAML
deploy_staging:
  extends: .deploy
  stage: staging
  variables:
    DEPLOY_TARGET: staging
  environment:
    name: staging
    url: https://staging.example.com
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

deploy_production:
  extends: .deploy
  stage: production
  variables:
    DEPLOY_TARGET: production
  environment:
    name: production
    url: https://www.example.com
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual
  resource_group: production

when: manual makes the job wait for a person to press its play button. By default a manual job is optional and does not block later work; here nothing follows it, so that is fine. resource_group: production makes sure only one production deployment runs at a time, even when two pipelines reach this job together. For stricter control, mark production as a protected environment in the project settings so that only certain roles can deploy to it. That setting is outside the YAML, which means a pipeline author cannot bypass it by editing the file.

Stand-in: the environment lifecycle

GitLab stores each environment's state: available, stopping or stopped. A deploy job creates or updates an environment; a stop job (or auto_stop_in) ends it. The simulation below models merge request events and shows which environments exist after each step. It is not GitLab, but it makes the on_stop idea concrete.

JS Review environments over time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second push to the same merge request redeploys the same environment instead of creating a new one (deploys=2), because the name is stable. Merging stops the review environment but keeps its record, which is how GitLab can show you history. Staging is created by the main pipeline.

Stand-in: which jobs a pipeline contains

The rules and workflow:rules above decide which jobs exist in each pipeline. This second stand-in evaluates them for a few pipeline kinds. It supports only the simple == comparisons and truthiness checks used in this project, so it demonstrates the idea and is not a general GitLab expression engine.

JS Evaluating rules for pipeline kinds

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pushing to a branch that has an open merge request creates no extra pipeline, which is exactly the duplicate-pipeline protection from step 1.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project use workflow:rules?

    workflow:rules runs before any job rules. It can drop a branch pipeline when a merge request pipeline already covers the same commit.
  2. 2. What links a review environment to the job that cleans it up?

    The deploy job lists the stop job in on_stop, and the stop job declares the same environment with action: stop. GitLab runs it when the branch is merged or deleted.
  3. 3. Why does the stop job set GIT_STRATEGY: none?

    When a branch is deleted after a merge, a checkout would fail. The stop job must not depend on the repository contents.
  4. 4. What does when: manual do on deploy_production?

    A manual job is created but not started automatically. Combined with a protected environment, it limits who can release.
  5. 5. What does resource_group: production prevent?

    Jobs in the same resource group run one at a time, so overlapping pipelines cannot deploy to production concurrently.

Summary

  • workflow:rules filters pipelines so a commit does not get both a branch and a merge request pipeline.
  • Hidden jobs and extends keep deploy logic in one place; include splits large files.
  • A review app uses a dynamic environment name built from $CI_COMMIT_REF_SLUG, with on_stop and auto_stop_in for cleanup.
  • The stop job declares action: stop and avoids needing a checkout.
  • Staging deploys automatically from the default branch; production is a manual job in a resource_group, ideally a protected environment.
  • The YAML is read-only here; the simulations only model environments and rules.

Next: Project: Release Automation for a Monorepo