pipeline { agent any environment { REGISTRY = "docker.io/adelyao" APP_NAME = "employee" MANIFEST_REPO = "https://git.winteraccess.id/adel/Employee-manifest.git" MANIFEST_CRED_ID = "GIT_CRED_ID" DOCKER_CRED_ID = "DOCKER_CRED_ID" BRANCH = "main" } parameters { string(name: 'IMAGE_TAG', defaultValue: '', description: 'Image tag (e.g., commit SHA or build number)') } stages { stage('Prepare Workspace') { steps { cleanWs() checkout scm // ✅ otomatis clone repo Gitea tempat Jenkinsfile berada } } stage('Install yq') { steps { sh ''' if ! command -v yq &> /dev/null; then echo "Installing yq..." wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq chmod +x /usr/local/bin/yq else echo "yq already installed" fi yq --version ''' } } stage('Build and Push Docker Images') { steps { script { def tag = params.IMAGE_TAG ?: "build-${env.BUILD_NUMBER}" echo "Building and pushing image with tag: ${tag}" withCredentials([usernamePassword(credentialsId: env.DOCKER_CRED_ID, usernameVariable: 'DOCKER_USER', passwordVariable: 'DOCKER_PASS')]) { sh """ echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin docker build -t ${REGISTRY}/${APP_NAME}-be:${tag} ./employee-be docker build -t ${REGISTRY}/${APP_NAME}-fe:${tag} ./employee-fe docker push ${REGISTRY}/${APP_NAME}-be:${tag} docker push ${REGISTRY}/${APP_NAME}-fe:${tag} docker logout """ } env.IMAGE_TAG_FINAL = tag } } } stage('Checkout Manifest Repo') { steps { dir('manifest') { checkout([$class: 'GitSCM', branches: [[name: env.BRANCH]], userRemoteConfigs: [[ url: env.MANIFEST_REPO, credentialsId: env.MANIFEST_CRED_ID ]] ]) } } } stage('Update Image Tags in Manifests') { steps { dir('manifest') { script { echo "Updating manifests to tag: ${env.IMAGE_TAG_FINAL}" sh """ yq e -i '.spec.template.spec.containers[0].image = "${REGISTRY}/${APP_NAME}-be:${env.IMAGE_TAG_FINAL}"' base/backend-deployment.yaml yq e -i '.spec.template.spec.containers[0].image = "${REGISTRY}/${APP_NAME}-fe:${env.IMAGE_TAG_FINAL}"' base/frontend-deployment.yaml """ } } } } stage('Commit & Push Manifest Updates') { steps { dir('manifest') { withCredentials([usernamePassword(credentialsId: env.MANIFEST_CRED_ID, usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')]) { sh """ git config user.email "jenkins@local" git config user.name "jenkins" git add -A git diff --staged --quiet || (git commit -m "chore: update image to ${env.IMAGE_TAG_FINAL}" && git push https://${GIT_USER}:${GIT_PASS}@${env.MANIFEST_REPO.replace('https://', '')} ${env.BRANCH}) """ echo "✅ Manifest repo updated successfully" } } } } stage('ArgoCD Sync (optional)') { steps { echo "If ArgoCD auto-sync is enabled, deployment will update automatically." } } } post { success { echo "🎉 GitOps pipeline completed successfully!" } failure { echo "❌ Pipeline failed. Check previous logs." } } }