Monday, 23 June 2025

Jenkins - 1

Section 

Description 

parameters 

Accepts user input before build: branch, environment, flags. 

environment 

Defines environment variables, including credential bindings. 

options 

Controls build retention, timeout, log formatting. 

triggers 

Automatically starts pipeline on SCM change or schedule. 

stages > parallel 

Runs stages in parallel (e.g., lint & coverage). 

when 

Conditional execution of stages (e.g., test only if RUN_TESTS == true). 

stash/unstash 

Transfers files between stages/nodes. 

input 

Manual approval before deploy (great for production safety). 

docker.withRegistry 

Builds and pushes Docker image using Docker Hub credentials. 

post 

Sends email notifications and performs cleanup actions. 

 

Groovy 


@Library('my-shared-library') _  // Shared Library reference (optional)


pipeline {

  agent any // Use any available Jenkins agent


  // Define input parameters

  parameters {

    string(name: 'BRANCH', defaultValue: 'main', description: 'Git branch to build')

    booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests or not')

    choice(name: 'ENVIRONMENT', choices: ['dev', 'stage', 'prod'], description: 'Deployment environment')

  }


  // Define environment variables

  environment {

    APP_NAME = 'my-app'

    DEPLOY_USER = credentials('deploy-ssh-user') // Jenkins credentials

    IMAGE_TAG = "${env.BUILD_NUMBER}"

  }


  options {

    buildDiscarder(logRotator(numToKeepStr: '10')) // Keep only last 10 builds

    timeout(time: 15, unit: 'MINUTES') // Pipeline timeout

    timestamps() // Show timestamps in logs

  }


  triggers {

    pollSCM('H/15 * * * *') // Poll every 15 mins (alternative: GitHub webhook)

  }


  stages {


    stage('Checkout') {

      steps {

        checkout scm

        echo "Checked out branch: ${params.BRANCH}"

      }

    }


    stage('Build') {

      steps {

        sh './gradlew clean build'

        stash name: 'build-output', includes: '**/build/libs/*.jar'

      }

    }


    stage('Static Analysis') {

      parallel {

        stage('Lint') {

          steps {

            sh './gradlew lint'

          }

        }

        stage('Code Coverage') {

          steps {

            sh './gradlew test jacocoTestReport'

            junit 'build/test-results/test/*.xml'

          }

        }

      }

    }


    stage('Test') {

      when {

        expression { return params.RUN_TESTS }

      }

      steps {

        sh './gradlew test'

      }

    }


    stage('Approval') {

      when {

        branch 'main'

      }

      steps {

        input message: "Approve deployment to ${params.ENVIRONMENT}?"

      }

    }


    stage('Deploy') {

      agent { label 'linux' } // Run this on a specific labeled agent

      steps {

        unstash 'build-output'

        sh "scp build/libs/*.jar ${DEPLOY_USER}@prod-server:/deployments/"

        echo "Deployed version ${env.IMAGE_TAG} to ${params.ENVIRONMENT}"

      }

    }


    stage('Docker Build & Push') {

      steps {

        script {

          docker.withRegistry('https://index.docker.io/v1/', 'dockerhub-credentials') {

            def app = docker.build("${APP_NAME}:${env.IMAGE_TAG}")

            app.push()

          }

        }

      }

    }


    stage('Notify') {

      steps {

        echo "Build completed for ${params.BRANCH} on ${params.ENVIRONMENT}"

      }

    }

  }


  post {

    always {

      echo 'Cleaning up...'

      cleanWs()

    }

    success {

      emailext(

        subject: "SUCCESS: Build #${env.BUILD_NUMBER} for ${env.JOB_NAME}",

        body: "Good news!\n\nBuild succeeded: ${env.BUILD_URL}",

        to: 'dev-team@example.com'

      )

    }

    failure {

      emailext(

        subject: "FAILURE: Build #${env.BUILD_NUMBER} for ${env.JOB_NAME}",

        body: "Build failed: ${env.BUILD_URL}\n\nPlease check the console output.",

        to: 'dev-team@example.com'

      )

    }

  }

}


No comments:

Post a Comment