def PIPELINE_ID = "${env.BUILD_NUMBER}" def getImageTag() { def dateFormat = new java.text.SimpleDateFormat('yyyyMMddHHmmss') def currentDate = new Date() return dateFormat.format(currentDate) } podTemplate( label: "${PIPELINE_ID}", serviceAccount: 'jenkins', slaveConnectTimeout: 300, idleMinutes: 1, activeDeadlineSeconds: 3600, podRetention: never(), yaml: ''' spec: terminationGracePeriodSeconds: 3 restartPolicy: Never tolerations: - effect: NoSchedule key: dedicated operator: Equal value: cicd ''', containers: [ containerTemplate( name: 'podman', image: "mgoltzsche/podman", ttyEnabled: true, command: 'cat', privileged: true, resourceRequestCpu: '500m', resourceRequestMemory: '2Gi', resourceLimitCpu: '2000m', resourceLimitMemory: '4Gi' ), containerTemplate( name: 'gradle', image: 'gradle:jdk21', ttyEnabled: true, command: 'cat', resourceRequestCpu: '500m', resourceRequestMemory: '1Gi', resourceLimitCpu: '1000m', resourceLimitMemory: '2Gi', envVars: [ envVar(key: 'DOCKER_HOST', value: 'unix:///run/podman/podman.sock'), envVar(key: 'TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE', value: '/run/podman/podman.sock'), envVar(key: 'TESTCONTAINERS_RYUK_DISABLED', value: 'true') ] ), containerTemplate( name: 'git', image: 'alpine/git:latest', command: 'cat', ttyEnabled: true, resourceRequestCpu: '100m', resourceRequestMemory: '256Mi', resourceLimitCpu: '300m', resourceLimitMemory: '512Mi' ) ], volumes: [ emptyDirVolume(mountPath: '/home/gradle/.gradle', memory: false), emptyDirVolume(mountPath: '/run/podman', memory: false) ] ) { node(PIPELINE_ID) { def imageTag = getImageTag() def environment = params.ENVIRONMENT ?: 'dev' def services = ['user', 'meeting', 'stt', 'notification'] def registry = 'acrdigitalgarage02.azurecr.io' def imageOrg = 'hgzero' try { stage("Get Source") { checkout scm // 환경 변수 로드 def configFile = ".github/config/deploy_env_vars_${environment}" if (fileExists(configFile)) { echo "📋 Loading environment variables for ${environment}..." def props = readProperties file: configFile echo "Config loaded: ${props}" } } stage('Build') { container('gradle') { echo "🔨 Building with Gradle..." sh """ chmod +x gradlew ./gradlew build -x test """ } } stage('Archive Artifacts') { echo "📦 Archiving build artifacts..." archiveArtifacts artifacts: '**/build/libs/*.jar', fingerprint: true } stage('Build & Push Images') { timeout(time: 30, unit: 'MINUTES') { container('podman') { withCredentials([ usernamePassword( credentialsId: 'acr-credentials', usernameVariable: 'ACR_USERNAME', passwordVariable: 'ACR_PASSWORD' ), usernamePassword( credentialsId: 'dockerhub-credentials', usernameVariable: 'DOCKERHUB_USERNAME', passwordVariable: 'DOCKERHUB_PASSWORD' ) ]) { echo "🐳 Building and pushing Docker images..." // Login to Docker Hub (prevent rate limit) sh "podman login docker.io --username \$DOCKERHUB_USERNAME --password \$DOCKERHUB_PASSWORD" // Login to Azure Container Registry sh "podman login ${registry} --username \$ACR_USERNAME --password \$ACR_PASSWORD" // Build and push each service services.each { service -> echo "Building ${service}..." def imageTagFull = "${registry}/${imageOrg}/${service}:${environment}-${imageTag}" sh """ podman build \\ --build-arg BUILD_LIB_DIR="${service}/build/libs" \\ --build-arg ARTIFACTORY_FILE="${service}.jar" \\ -f deployment/container/Dockerfile-backend \\ -t ${imageTagFull} . """ echo "Pushing ${service}..." sh "podman push ${imageTagFull}" echo "✅ ${service} image pushed: ${imageTagFull}" } } } } } stage('Update Manifest Repository') { container('git') { withCredentials([usernamePassword( credentialsId: 'github-credentials-dg0506', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_TOKEN' )]) { echo "📝 Updating manifest repository..." sh """ # 매니페스트 레포지토리 클론 REPO_URL=\$(echo "https://github.com/hjmoons/hgzero-manifest.git" | sed 's|https://||') git clone https://\${GIT_USERNAME}:\${GIT_TOKEN}@\${REPO_URL} manifest-repo cd manifest-repo # 각 서비스별 이미지 태그 업데이트 (sed 사용) cd hgzero-back/kustomize/base services="user meeting stt notification" for service in \$services; do echo "Updating \$service image tag..." sed -i "s|image: ${registry}/${imageOrg}/\$service:.*|image: ${registry}/${imageOrg}/\$service:${environment}-${imageTag}|g" \\ \$service/deployment.yaml # 변경 사항 확인 echo "Updated \$service deployment.yaml:" grep "image: ${registry}/${imageOrg}/\$service" \$service/deployment.yaml done # Git 설정 및 푸시 cd ../../.. git config user.name "Jenkins" git config user.email "jenkins@hgzero.com" git add . git commit -m "🚀 Update hgzero ${environment} images to ${environment}-${imageTag}" git push origin main echo "✅ 매니페스트 업데이트 완료. ArgoCD가 자동으로 배포합니다." """ } } } stage('Pipeline Complete') { echo "🧹 Pipeline completed. Pod cleanup handled by Jenkins Kubernetes Plugin." if (currentBuild.result == null || currentBuild.result == 'SUCCESS') { echo "✅ Pipeline completed successfully!" echo "Environment: ${environment}" echo "Image Tag: ${imageTag}" } else { echo "❌ Pipeline failed with result: ${currentBuild.result}" } } } catch (Exception e) { currentBuild.result = 'FAILURE' echo "❌ Pipeline failed with exception: ${e.getMessage()}" throw e } finally { echo "🧹 Cleaning up resources and preparing for pod termination..." echo "Pod will be terminated in 3 seconds due to terminationGracePeriodSeconds: 3" } } }