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.
More on Write-a-pipeline tasks
Write a GitHub Actions workflow that runs tests on every PR and push to main.BeginnerWrite a workflow that builds a Docker image and pushes it to ECR using OIDC (no access keys).IntermediateWrite a matrix job that tests on Python 3.10, 3.11 and 3.12 on Linux and Windows.BeginnerWrite a declarative Jenkinsfile with build, test, Docker push and a manual approval before prod.AdvancedWrite a GitHub Actions deploy job that requires approval for production using environments.BeginnerWrite a reusable workflow and call it from another repo.Intermediate