the-tip-top-backend/Jenkinsfile

157 lines
5.8 KiB
Groovy
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

pipeline {
agent any
// 🔁 Vérifie toutes les 2 minutes si du nouveau code a été poussé
triggers {
pollSCM('H/2 * * * *')
}
// ⚙️ Paramètre manuel (fallback)
parameters {
choice(
name: 'ENV',
choices: ['dev', 'preprod', 'prod'],
description: 'Choisir lenvironnement de déploiement (automatique si branche correspondante)'
)
}
environment {
REGISTRY_URL = "registry.wk-archi-o24a-15m-g3.fr"
IMAGE_NAME = "the-tip-top-backend"
}
stages {
/* ───────────────────────────────
* 1⃣ Init — Détection automatique de lenvironnement
* ─────────────────────────────── */
stage('Init') {
steps {
script {
// 🔍 Détermine la branche Git courante
def currentBranch = sh(script: "git rev-parse --abbrev-ref HEAD", returnStdout: true).trim()
echo "🧭 Branche détectée : ${currentBranch}"
// 🧩 Si la branche correspond à un environnement connu, on lutilise
if (["dev", "preprod", "main"].contains(currentBranch)) {
env.ENV = (currentBranch == "main") ? "prod" : currentBranch
} else {
env.ENV = params.ENV ?: "dev"
}
// 🧱 Variables de déploiement dérivées
env.TAG = "${env.ENV}-latest"
env.DEPLOY_PATH = "/srv/devops/the-tip-top/${env.ENV}"
echo """
🌍 Environnement = ${env.ENV}
🏷️ Tag Docker = ${env.TAG}
📂 Chemin de déploiement = ${env.DEPLOY_PATH}
"""
}
}
}
stage('Checkout') {
steps {
echo "📦 Récupération du code source depuis Gitea..."
checkout scm
}
}
stage('Tests & Qualité') {
steps {
echo "🧪 Lancement des tests et analyse de code..."
sh '''
npm ci
npm run lint || echo "⚠️ Erreurs de lint détectées"
npm test || echo "⚠️ Tests échoués — vérifier les logs"
'''
}
}
stage('Build Docker image') {
steps {
echo "🐳 Construction de limage Docker backend..."
sh """
docker build -t ${REGISTRY_URL}/${IMAGE_NAME}:${TAG} .
docker tag ${REGISTRY_URL}/${IMAGE_NAME}:${TAG} ${REGISTRY_URL}/${IMAGE_NAME}:latest
"""
}
}
stage('Push to Registry') {
steps {
echo "📤 Envoi de limage vers le registre Docker privé..."
withCredentials([usernamePassword(credentialsId: 'registry-credentials', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) {
sh """
echo "$REG_PASS" | docker login ${REGISTRY_URL} -u "$REG_USER" --password-stdin
docker push ${REGISTRY_URL}/${IMAGE_NAME}:${TAG}
docker push ${REGISTRY_URL}/${IMAGE_NAME}:latest
"""
}
}
}
stage('Backup Before Deploy') {
steps {
echo "💾 Exécution du script de sauvegarde avant déploiement..."
sh '''
if [ -f /srv/devops/the-tip-top/backup.sh ]; then
bash /srv/devops/the-tip-top/backup.sh
else
echo "⚠️ Aucun script backup.sh trouvé."
fi
'''
}
}
stage('Deploy') {
steps {
echo "🚀 Déploiement du backend sur ${env.ENV}..."
sh '''
if [ ! -f "${DEPLOY_PATH}/docker-compose.yml" ]; then
echo "❌ Fichier docker-compose.yml introuvable dans ${DEPLOY_PATH}"
exit 1
fi
cd "${DEPLOY_PATH}"
docker compose pull backend
docker compose up -d --force-recreate backend
'''
}
}
stage('Health Check') {
steps {
echo "🩺 Vérification du backend après déploiement..."
script {
def domain = (env.ENV == 'dev') ? "api.dev.dsp5-archi-o24a-15m-g3.fr" :
(env.ENV == 'preprod') ? "api.preprod.dsp5-archi-o24a-15m-g3.fr" :
"api.dsp5-archi-o24a-15m-g3.fr"
def statusCode = "000"
for (int i = 1; i <= 10; i++) {
statusCode = sh(script: "curl -k -s -o /dev/null -w '%{http_code}' https://${domain}/health || echo 000", returnStdout: true).trim()
if (statusCode in ['200', '301', '302']) {
echo "✅ Backend ${env.ENV} opérationnel (HTTP ${statusCode})"
return
}
echo "⏳ Tentative ${i}/10 → HTTP ${statusCode}"
sleep 5
}
error("❌ Health check échoué - code HTTP ${statusCode}")
}
}
}
}
post {
success {
echo "✅ Pipeline backend ${env.ENV} terminé avec succès !"
}
failure {
echo "❌ Échec du pipeline backend pour ${env.ENV}."
}
}
}