pipeline { agent any environment { GITEA_REPO = 'https://code.jacquesingram.online/lenape/nvhi-atsila-microservice.git' GITEA_CREDS = '52ee0829-6e65-4951-925b-4186254c3f21' SONAR_HOST = 'https://sonar.jacquesingram.online' SONAR_TOKEN = credentials('sonar-token') AWS_CRED_ID = 'aws-ci' AWS_ACCOUNT_ID = credentials('AWS_ACCOUNT_ID') AWS_REGION = 'us-east-2' ECR_REPO = 'nvhi-atsila-microservice' // Backend configuration TF_BACKEND_BUCKET = 'nvhi-atsila-tf-state' TF_BACKEND_PREFIX = 'ecs/terraform.tfstate' TF_DDB_TABLE = 'nvhi-atsila-locks' SSH_CRED_ID = 'jenkins-ssh' // Application variables TF_VAR_cluster_name = 'nvhi-atsila-cluster' TF_VAR_vpc_cidr = '10.0.0.0/16' TF_VAR_public_subnets = '10.0.1.0/24,10.0.2.0/24' TF_VAR_instance_type = 't2.micro' TF_VAR_key_pair_name = 'nvhi-atsila-deployer' TF_VAR_jenkins_ip_cidr = "${JENKINS_SSH_CIDR}/32" TF_VAR_aws_region = "${AWS_REGION}" IMAGE_NAME = "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}" IMAGE_TAG = "v1.0.${BUILD_NUMBER}" // Enterprise settings TF_IN_AUTOMATION = 'true' TF_INPUT = 'false' } stages { stage('Checkout') { steps { checkout scm script { // Archive the Git commit for traceability def gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim() currentBuild.description = "Commit: ${gitCommit.take(8)}" echo "🚀 Starting deployment for commit: ${gitCommit.take(8)}" } } } stage('Security & Quality Checks') { parallel { stage('SonarQube Analysis') { steps { script { def scannerHome = tool 'SonarQubeScanner' withSonarQubeEnv('SonarQube') { sh """ ${scannerHome}/bin/sonar-scanner \ -Dsonar.projectKey=nvhi-atsila-microservice \ -Dsonar.sources=. \ -Dsonar.projectVersion=${BUILD_NUMBER} """ } } } } stage('Terraform Validation') { steps { script { echo "🔒 Running Terraform security and validation checks..." sh ''' echo "Validating Terraform configuration..." cd terraform && terraform init -backend=false terraform validate echo "✅ Terraform validation passed" ''' } } } } } stage('Build & Push Container') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { sh ''' echo "🔐 Logging into ECR..." aws ecr get-login-password --region $AWS_REGION \ | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com ''' script { echo "🐳 Building container image..." def img = docker.build("${IMAGE_NAME}:${IMAGE_TAG}") echo "📤 Pushing to ECR..." img.push() img.push("latest") // Also tag as latest for convenience echo "✅ Container pushed successfully: ${IMAGE_NAME}:${IMAGE_TAG}" } } } } stage('Bootstrap Backend Infrastructure') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { dir('terraform-backend') { script { echo "🏗️ Checking backend infrastructure..." // Check if backend resources exist def backendExists = sh( script: ''' if aws s3api head-bucket --bucket $TF_BACKEND_BUCKET 2>/dev/null && \ aws dynamodb describe-table --table-name $TF_DDB_TABLE 2>/dev/null; then echo "true" else echo "false" fi ''', returnStdout: true ).trim() if (backendExists == "false") { echo "📦 Backend infrastructure doesn't exist. Creating..." sh ''' terraform init terraform plan -out=backend.tfplan \ -var="aws_region=$AWS_REGION" \ -var="backend_bucket_name=$TF_BACKEND_BUCKET" \ -var="lock_table_name=$TF_DDB_TABLE" terraform apply backend.tfplan ''' echo "✅ Backend infrastructure created successfully" } else { echo "✅ Backend infrastructure already exists. Continuing..." } } } } } } stage('Infrastructure State Management') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { dir('terraform') { script { echo "🔄 Managing infrastructure state and provider upgrades..." sh ''' # Initialize with remote backend terraform init \ -backend-config="bucket=${TF_BACKEND_BUCKET}" \ -backend-config="key=${TF_BACKEND_PREFIX}" \ -backend-config="region=${AWS_REGION}" \ -backend-config="dynamodb_table=${TF_DDB_TABLE}" # Backup current state (enterprise best practice) echo "💾 Backing up current state..." terraform state pull > "state-backup-${BUILD_NUMBER}.json" # Upgrade providers to handle version conflicts echo "⬆️ Upgrading providers..." terraform init -upgrade # Create execution plan echo "📋 Creating execution plan..." terraform plan -out="tfplan-${BUILD_NUMBER}" \ -var="cluster_name=${TF_VAR_cluster_name}" \ -var="vpc_cidr=${TF_VAR_vpc_cidr}" \ -var="public_subnets=${TF_VAR_public_subnets}" \ -var="instance_type=${TF_VAR_instance_type}" \ -var="key_pair_name=${TF_VAR_key_pair_name}" \ -var="jenkins_ip_cidr=${TF_VAR_jenkins_ip_cidr}" \ -var="aws_region=${TF_VAR_aws_region}" ''' // Archive state backup and plan for audit trail archiveArtifacts artifacts: "state-backup-${BUILD_NUMBER}.json,tfplan-${BUILD_NUMBER}", fingerprint: true, allowEmptyArchive: false echo "✅ Infrastructure planning completed" } } } } } stage('Deploy Infrastructure') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { dir('terraform') { script { echo "🚀 Deploying infrastructure changes..." sh """ # Apply the planned changes terraform apply "tfplan-${BUILD_NUMBER}" # Verify no unexpected drift echo "🔍 Verifying deployment consistency..." terraform plan -detailed-exitcode \ -var="cluster_name=${TF_VAR_cluster_name}" \ -var="vpc_cidr=${TF_VAR_vpc_cidr}" \ -var="public_subnets=${TF_VAR_public_subnets}" \ -var="instance_type=${TF_VAR_instance_type}" \ -var="key_pair_name=${TF_VAR_key_pair_name}" \ -var="jenkins_ip_cidr=${TF_VAR_jenkins_ip_cidr}" \ -var="aws_region=${TF_VAR_aws_region}" || echo "⚠️ Infrastructure drift detected - review required" """ echo "✅ Infrastructure deployment completed" } } } } } stage('Configure & Deploy Application') { parallel { stage('Configure EC2 Instance') { steps { script { def ec2_ip = sh( script: "terraform -chdir=terraform output -raw ecs_instance_public_ip", returnStdout: true ).trim() echo "🔧 Configuring EC2 instance: ${ec2_ip}" writeFile file: 'ansible/hosts', text: "[inventory_hosts]\n${ec2_ip} ansible_user=ec2-user" } ansiblePlaybook( playbook: 'ansible/configure_ecs.yml', inventory: 'ansible/hosts', credentialsId: env.SSH_CRED_ID ) echo "✅ EC2 configuration completed" } } stage('Deploy Application to ECS') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { script { echo "🚢 Deploying application version ${IMAGE_TAG}..." sh """ # Register new task definition with build metadata aws ecs register-task-definition \ --family ${TF_VAR_cluster_name} \ --network-mode bridge \ --container-definitions '[{ "name":"health-workload", "image":"${IMAGE_NAME}:${IMAGE_TAG}", "essential":true, "memory":512, "portMappings":[{"containerPort":8080,"hostPort":8080}], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/${TF_VAR_cluster_name}", "awslogs-region": "${AWS_REGION}", "awslogs-stream-prefix": "ecs" } }, "environment": [ {"name": "BUILD_NUMBER", "value": "${BUILD_NUMBER}"}, {"name": "GIT_COMMIT", "value": "${env.GIT_COMMIT ?: 'unknown'}"}, {"name": "DEPLOYMENT_TIME", "value": "${new Date().format('yyyy-MM-dd HH:mm:ss')}"} ] }]' \ --region ${AWS_REGION} # Perform rolling deployment aws ecs update-service \ --cluster ${TF_VAR_cluster_name} \ --service ${TF_VAR_cluster_name}-service \ --force-new-deployment \ --region ${AWS_REGION} # Wait for deployment to stabilize echo "⏳ Waiting for service deployment to stabilize..." aws ecs wait services-stable \ --cluster ${TF_VAR_cluster_name} \ --services ${TF_VAR_cluster_name}-service \ --region ${AWS_REGION} """ echo "✅ Application deployment completed" } } } } } } stage('Post-Deployment Validation') { parallel { stage('Health Check') { steps { script { def ec2_ip = sh( script: "terraform -chdir=terraform output -raw ecs_instance_public_ip", returnStdout: true ).trim() echo "🏥 Running health checks on http://${ec2_ip}:8080/health" timeout(time: 5, unit: 'MINUTES') { waitUntil { script { def response = sh( script: "curl -s -o /dev/null -w '%{http_code}' http://${ec2_ip}:8080/health || echo '000'", returnStdout: true ).trim() echo "Health check response: ${response}" if (response == "200") { echo "✅ Health check passed!" return true } else { echo "⏳ Waiting for application to be ready..." sleep(10) return false } } } } } } } stage('Smoke Tests') { steps { script { echo "💨 Running smoke tests..." def ec2_ip = sh( script: "terraform -chdir=terraform output -raw ecs_instance_public_ip", returnStdout: true ).trim() // Basic smoke tests sh """ echo "Testing application endpoints..." curl -f http://${ec2_ip}:8080/health || exit 1 echo "✅ All smoke tests passed" """ } } } } } } post { always { script { echo "📊 Collecting deployment artifacts and cleanup..." // Archive deployment artifacts archiveArtifacts artifacts: 'ansible/hosts', allowEmptyArchive: true // Clean workspace but preserve important files cleanWs(deleteDirs: true, notFailBuild: true) } } success { script { def ec2_ip = "" try { ec2_ip = sh( script: "terraform -chdir=terraform output -raw ecs_instance_public_ip", returnStdout: true ).trim() } catch (Exception e) { ec2_ip = "unknown" } echo "🎉 Deployment completed successfully!" echo "📋 Deployment Summary:" echo " • Environment: Production" echo " • Application Version: ${IMAGE_TAG}" echo " • Application URL: http://${ec2_ip}:8080" echo " • Build Number: ${BUILD_NUMBER}" echo " • Git Commit: ${env.GIT_COMMIT?.take(8) ?: 'unknown'}" currentBuild.description = "✅ Deployed ${IMAGE_TAG} to ${ec2_ip}" } } failure { script { echo "❌ Deployment failed!" echo "🔍 Check the logs above for details" echo "💡 State backup available: state-backup-${BUILD_NUMBER}.json" currentBuild.description = "❌ Failed at ${env.STAGE_NAME}" } } } }