Interview Prep/Real-World Interview/Write-a-pipeline tasks

Write a GitLab CI pipeline with build, test and deploy stages, caching and manual prod deploy.

IntermediateHands-onWrite-a-pipeline tasks
Answer
stages: [build, test, deploy]

variables:
  IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA

build:
  stage: build
  image: docker:27
  services: [docker:27-dind]
  script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
    - docker build -t "$IMAGE" .
    - docker push "$IMAGE"

test:
  stage: test
  image: node:22
  cache:
    key: { files: [package-lock.json] }
    paths: [.npm/]
  script:
    - npm ci --cache .npm --prefer-offline
    - npm test

deploy_prod:
  stage: deploy
  image: alpine/helm:3.16.2
  script:
    - helm upgrade --install app ./chart --set image.tag=$CI_COMMIT_SHORT_SHA
  environment: { name: production, url: https://app.example.com }
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual

Key trick → A cache key based on the lockfile only refreshes the cache when dependencies change. rules with when: manual adds a play button only on the default branch.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-a-pipeline tasks