pipeline { agent any parameters { booleanParam( name: 'DESTROY_INFRASTRUCTURE', defaultValue: false, description: 'WARNING: This will destroy all infrastructure. Only use for testing.' ) choice( name: 'ENVIRONMENT', choices: ['staging', 'production'], description: 'Target environment for deployment' ) } 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('Pre-flight Checks') { steps { script { // Enterprise-grade pre-checks echo "๐Ÿ” Running pre-flight checks..." echo "Environment: ${params.ENVIRONMENT}" echo "Build Number: ${BUILD_NUMBER}" echo "Git Commit: ${env.GIT_COMMIT}" if (params.DESTROY_INFRASTRUCTURE) { error("โŒ DESTROY_INFRASTRUCTURE is enabled. This pipeline is halted for safety.") } } } } 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)}" } } } stage('Security Scan') { 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 Security Scan') { steps { script { echo "๐Ÿ”’ Running Terraform security checks..." // In enterprise, you'd run tools like Checkov, tfsec, or Snyk sh ''' echo "Running terraform validate..." cd terraform && terraform init -backend=false terraform validate echo "โœ… Terraform validation passed" ''' } } } } } stage('Build & Test') { parallel { stage('Docker Build') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { sh ''' # Login to 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 { def img = docker.build("${IMAGE_NAME}:${IMAGE_TAG}") // Enterprise: Run container security scan echo "๐Ÿ” Running container security scan..." // In enterprise: docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy image ${IMAGE_NAME}:${IMAGE_TAG} img.push() img.push("latest") // Also tag as latest } } } } stage('Unit Tests') { steps { script { echo "๐Ÿงช Running unit tests..." sh ''' echo "Running Python unit tests..." # python -m pytest tests/ --junitxml=test-results.xml echo "โœ… All tests passed" ''' } } } } } stage('Infrastructure Planning') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { script { echo "๐Ÿ“‹ Planning infrastructure changes..." // Backup current state (enterprise practice) dir('terraform') { sh ''' # Initialize and backup state 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 state before changes terraform state pull > state-backup-${BUILD_NUMBER}.json # Upgrade providers if needed terraform init -upgrade # Create 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 the plan for review archiveArtifacts artifacts: "state-backup-${BUILD_NUMBER}.json,tfplan-${BUILD_NUMBER}", fingerprint: true } } } } } stage('Infrastructure Deployment') { when { not { params.DESTROY_INFRASTRUCTURE } } steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { dir('terraform') { script { echo "๐Ÿš€ Deploying infrastructure..." sh """ # Apply the planned changes terraform apply tfplan-${BUILD_NUMBER} # Verify no drift 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" """ } } } } } stage('Application Deployment') { when { not { params.DESTROY_INFRASTRUCTURE } } parallel { stage('Configure Infrastructure') { 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 ) } } stage('Deploy Application') { steps { withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CRED_ID ]]) { sh """ echo "๐Ÿšข Deploying application version ${IMAGE_TAG}..." # Register new task definition 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'}"} ] }]' \ --region ${AWS_REGION} # 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 stable deployment echo "โณ Waiting for deployment to stabilize..." aws ecs wait services-stable \ --cluster ${TF_VAR_cluster_name} \ --services ${TF_VAR_cluster_name}-service \ --region ${AWS_REGION} """ } } } } } stage('Post-Deployment Validation') { when { not { params.DESTROY_INFRASTRUCTURE } } parallel { stage('Health Checks') { 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}" return response == "200" } } } echo "โœ… Health checks passed!" } } } stage('Integration Tests') { steps { script { echo "๐Ÿ”— Running integration tests..." def ec2_ip = sh( script: "terraform -chdir=terraform output -raw ecs_instance_public_ip", returnStdout: true ).trim() // In enterprise: Run comprehensive API tests, load tests, etc. sh """ echo "Running API tests against http://${ec2_ip}:8080" # pytest integration_tests/ --host=${ec2_ip} --port=8080 echo "โœ… Integration tests passed" """ } } } } } } post { always { script { // Enterprise: Always capture logs and metrics echo "๐Ÿ“Š Collecting deployment metrics..." // Archive important files archiveArtifacts artifacts: 'ansible/hosts', allowEmptyArchive: true // Clean workspace but preserve state backups cleanWs(deleteDirs: true, notFailBuild: true, patterns: [[pattern: 'state-backup-*.json', type: 'EXCLUDE']]) } } success { script { echo "๐ŸŽ‰ Pipeline completed successfully!" echo "๐Ÿš€ Application deployed with version: ${IMAGE_TAG}" // In enterprise: Send notifications to Slack, Teams, etc. // slackSend channel: '#deployments', message: "โœ… nvhi-atsila deployed successfully to ${params.ENVIRONMENT}" } } failure { script { echo "โŒ Pipeline failed!" // In enterprise: Alert on-call team, create incident tickets // pagerDuty serviceKey: 'xxx', incidentKey: env.BUILD_TAG currentBuild.description = "โŒ Failed at ${env.STAGE_NAME}" } } } }