Files
nvhi-atsila-microservice/Jenkinsfile

405 lines
14 KiB
Plaintext
Raw Normal View History

2025-07-12 08:51:48 +00:00
pipeline {
agent any
2025-07-12 18:19:18 +00:00
2025-07-12 18:50:56 +00:00
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'
)
}
2025-07-12 08:51:48 +00:00
environment {
2025-07-12 09:23:38 +00:00
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')
2025-07-12 09:58:15 +00:00
2025-07-12 09:23:38 +00:00
AWS_CRED_ID = 'aws-ci'
2025-07-12 09:49:26 +00:00
AWS_ACCOUNT_ID = credentials('AWS_ACCOUNT_ID')
2025-07-12 09:23:38 +00:00
AWS_REGION = 'us-east-2'
2025-07-12 09:49:26 +00:00
ECR_REPO = 'nvhi-atsila-microservice'
2025-07-12 18:19:18 +00:00
// Backend configuration
2025-07-12 09:23:38 +00:00
TF_BACKEND_BUCKET = 'nvhi-atsila-tf-state'
TF_BACKEND_PREFIX = 'ecs/terraform.tfstate'
TF_DDB_TABLE = 'nvhi-atsila-locks'
2025-07-12 09:58:15 +00:00
2025-07-12 09:23:38 +00:00
SSH_CRED_ID = 'jenkins-ssh'
2025-07-12 08:51:48 +00:00
2025-07-12 18:19:18 +00:00
// Application variables
2025-07-12 09:23:38 +00:00
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'
2025-07-12 10:10:12 +00:00
TF_VAR_jenkins_ip_cidr = "${JENKINS_SSH_CIDR}/32"
2025-07-12 18:19:18 +00:00
TF_VAR_aws_region = "${AWS_REGION}"
2025-07-12 08:51:48 +00:00
2025-07-12 09:49:26 +00:00
IMAGE_NAME = "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}"
2025-07-12 09:23:38 +00:00
IMAGE_TAG = "v1.0.${BUILD_NUMBER}"
2025-07-12 18:50:56 +00:00
// Enterprise settings
TF_IN_AUTOMATION = 'true'
TF_INPUT = 'false'
2025-07-12 08:51:48 +00:00
}
2025-07-12 09:58:15 +00:00
2025-07-12 08:51:48 +00:00
stages {
2025-07-12 18:50:56 +00:00
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.")
}
}
2025-07-12 18:19:18 +00:00
}
2025-07-12 08:51:48 +00:00
}
2025-07-12 09:58:15 +00:00
2025-07-12 18:50:56 +00:00
stage('Checkout') {
steps {
checkout scm
2025-07-12 09:30:51 +00:00
script {
2025-07-12 18:50:56 +00:00
// Archive the Git commit for traceability
def gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
currentBuild.description = "Commit: ${gitCommit.take(8)}"
2025-07-12 08:51:48 +00:00
}
}
}
2025-07-12 09:58:15 +00:00
2025-07-12 18:50:56 +00:00
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"
'''
}
}
2025-07-12 09:49:26 +00:00
}
}
}
2025-07-12 09:58:15 +00:00
2025-07-12 18:50:56 +00:00
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"
'''
}
}
2025-07-12 08:51:48 +00:00
}
}
}
2025-07-12 09:58:15 +00:00
2025-07-12 18:50:56 +00:00
stage('Infrastructure Planning') {
2025-07-12 09:58:15 +00:00
steps {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: env.AWS_CRED_ID
]]) {
2025-07-12 18:50:56 +00:00
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
2025-07-12 18:19:18 +00:00
}
}
2025-07-12 09:58:15 +00:00
}
}
}
2025-07-12 18:50:56 +00:00
stage('Infrastructure Deployment') {
when {
not { params.DESTROY_INFRASTRUCTURE }
}
2025-07-12 08:51:48 +00:00
steps {
2025-07-12 09:49:26 +00:00
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: env.AWS_CRED_ID
]]) {
2025-07-12 08:51:48 +00:00
dir('terraform') {
2025-07-12 18:50:56 +00:00
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"
"""
}
2025-07-12 08:51:48 +00:00
}
}
}
}
2025-07-12 09:58:15 +00:00
2025-07-12 18:50:56 +00:00
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
)
}
2025-07-12 08:51:48 +00:00
}
2025-07-12 18:19:18 +00:00
2025-07-12 18:50:56 +00:00
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}
2025-07-12 08:51:48 +00:00
2025-07-12 18:50:56 +00:00
# Rolling deployment
aws ecs update-service \
--cluster ${TF_VAR_cluster_name} \
--service ${TF_VAR_cluster_name}-service \
--force-new-deployment \
--region ${AWS_REGION}
2025-07-12 18:19:18 +00:00
2025-07-12 18:50:56 +00:00
# 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}
"""
}
}
2025-07-12 08:51:48 +00:00
}
}
}
2025-07-12 18:19:18 +00:00
2025-07-12 18:50:56 +00:00
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"
}
}
2025-07-12 18:19:18 +00:00
}
2025-07-12 18:50:56 +00:00
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"
"""
2025-07-12 18:19:18 +00:00
}
}
}
}
}
}
post {
always {
2025-07-12 18:50:56 +00:00
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']])
}
2025-07-12 18:19:18 +00:00
}
success {
2025-07-12 18:50:56 +00:00
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}"
}
2025-07-12 18:19:18 +00:00
}
failure {
2025-07-12 18:50:56 +00:00
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}"
}
2025-07-12 18:19:18 +00:00
}
2025-07-12 08:51:48 +00:00
}
2025-07-12 18:19:18 +00:00
}