the-tip-top-backend/Jenkinsfile
2025-11-03 23:17:36 +01:00

169 lines
6.0 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
triggers {
pollSCM('H/2 * * * *')
}
parameters {
choice(
name: 'ENV',
choices: ['dev', 'preprod', 'prod'],
description: 'Choisir lenvironnement de déploiement'
)
}
environment {
REGISTRY_URL = "registry.wk-archi-o24a-15m-g3.fr"
IMAGE_NAME = "the-tip-top-backend"
}
stages {
stage('Init') {
steps {
script {
def currentBranch = sh(script: "git rev-parse --abbrev-ref HEAD", returnStdout: true).trim()
echo "🧭 Branche détectée : ${currentBranch}"
if (["dev", "preprod", "main"].contains(currentBranch)) {
env.ENV = (currentBranch == "main") ? "prod" : currentBranch
} else {
env.ENV = params.ENV ?: "dev"
}
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}
"""
sh "ls -l ${env.DEPLOY_PATH} || echo '⚠️ Dossier non accessible depuis Jenkins'"
}
}
}
stage('Checkout') {
steps {
echo "📦 Récupération du code source depuis Gitea..."
checkout scm
}
}
stage('Tests & Qualité') {
agent {
docker {
image 'node:18-alpine'
args '-u root'
}
}
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 (no cache)..."
sh """
docker build --no-cache -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 """
echo "📂 DEPLOY_PATH utilisé : ${DEPLOY_PATH}"
if [ ! -f "${DEPLOY_PATH}/docker-compose.yml" ]; then
echo "❌ Fichier docker-compose.yml introuvable dans ${DEPLOY_PATH}"
ls -l ${DEPLOY_PATH} || echo "⚠️ Impossible de lister le contenu."
exit 1
fi
cd "${DEPLOY_PATH}"
echo "📦 Pull de l'image Docker depuis le registre..."
docker compose pull backend
echo "🔄 Recréation du conteneur backend..."
docker compose up -d --force-recreate backend
"""
}
}
/* ───────────────────────────────
* 8⃣ Vérification de santé (via /health)
* ─────────────────────────────── */
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}."
}
}
}