the-tip-top-backend/Jenkinsfile

186 lines
7.9 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 {
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'"
}
}
}
/* ───────────────────────────────
* 2⃣ Checkout du code
* ─────────────────────────────── */
stage('Checkout') {
steps {
echo "📦 Récupération du code source depuis Gitea..."
checkout scm
}
}
/* ───────────────────────────────
* 3⃣ Tests & Qualité
* ─────────────────────────────── */
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"
'''
}
}
/* ───────────────────────────────
* 4⃣ Build de limage Docker
* ─────────────────────────────── */
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
"""
}
}
/* ───────────────────────────────
* 5⃣ Push vers le registre privé
* ─────────────────────────────── */
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
"""
}
}
}
/* ───────────────────────────────
* 6⃣ Backup avant déploiement
* ─────────────────────────────── */
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
'''
}
}
/* ───────────────────────────────
* 7⃣ Déploiement
* ─────────────────────────────── */
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}"
echo "Contenu du dossier :"
ls -l ${DEPLOY_PATH}
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é
* ─────────────────────────────── */
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 Actions
* ─────────────────────────────── */
post {
success {
echo "✅ Pipeline backend ${env.ENV} terminé avec succès !"
}
failure {
echo "❌ Échec du pipeline backend pour ${env.ENV}."
}
}
}