Le fichier .gitlab-ci.yml
GitLab CI/CD est configure par un fichier .gitlab-ci.yml a la racine du projet. Chaque push declenche le pipeline.
Pipeline complet : du code a la production
# .gitlab-ci.yml - Pipeline complet
stages:
- test
- build
- deploy-staging
- deploy-production
variables:
DOCKER_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
KUBE_NAMESPACE: mon-app
# ── Etape 1 : Tests ──
test:
stage: test
image: node:18-alpine
script:
- npm ci
- npm run lint
- npm run test:unit
- npm run test:integration
artifacts:
reports:
junit: test-results.xml
# ── Etape 2 : Build Docker ──
build:
stage: build
image: docker:24
services:
- docker:24-dind
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
script:
- docker build -t $DOCKER_IMAGE .
- docker push $DOCKER_IMAGE
only:
- main
- merge_requests
# ── Etape 3 : Deploy Staging ──
deploy-staging:
stage: deploy-staging
image: bitnami/kubectl:latest
script:
- kubectl config use-context gitlab-agent:mon-projet
- |
kubectl set image deployment/mon-app \
mon-app=$DOCKER_IMAGE \
-n $KUBE_NAMESPACE-staging
- kubectl rollout status deployment/mon-app -n $KUBE_NAMESPACE-staging
environment:
name: staging
url: https://staging.mon-app.example.com
# ── Etape 4 : Deploy Production ──
deploy-production:
stage: deploy-production
image: bitnami/kubectl:latest
script:
- kubectl config use-context gitlab-agent:mon-projet
- |
kubectl set image deployment/mon-app \
mon-app=$DOCKER_IMAGE \
-n $KUBE_NAMESPACE-production
- kubectl rollout status deployment/mon-app -n $KUBE_NAMESPACE-production
environment:
name: production
url: https://mon-app.example.com
when: manual # Deploiement manuel en production
only:
- main
Comprendre le flux
git push origin main
|
v
[test] --> npm test, lint
|
v
[build] --> docker build + push vers registry GitLab
|
v
[deploy-staging] --> kubectl set image (automatique)
|
v
[deploy-production] --> kubectl set image (bouton manuel)
Variables CI : GitLab fournit des variables predefinies comme $CI_COMMIT_SHORT_SHA (hash court du commit), $CI_REGISTRY (URL du registry), $CI_PIPELINE_ID, etc.