Simple JenkinsFile for Jenkins Pipeline.

Jenkins is a popular open-source automation server used for continuous integration and continuous deployment, enabling efficient software development through automated build, test, and deployment processes.

This simple JenkinsFile will help you deploy your maven project easily in different environments based on master, develop, feature, hotfix or release branch or tags. You can copy this and customize based on your need.

pipeline {
agent { label 'jenkins-agent-maven-311' }
options {
    buildDiscarder(logRotator(numToKeepStr:'10'))
    disableConcurrentBuilds()
}

environment {
    def APP_NAME = 'Your Project Name'
    def EMAIL_NOTIFICATION_LIST = 'Your or team email'
    def VERSION = readMavenPom().getVersion()
    def RELEASE_VERSION = null
    def BUILD_TYPE = null
}

stages {
    stage('Build') {
        steps {
            echo "starting build"
            echo "pom VERSION = ${VERSION}" //You can add branch, time it started and other too

            script {
                def isTag = sh(returnStdout: true, script: "git tag --contains | head -1").trim()

                if ("${env.BRANCH_NAME}" == 'master' && "${VERSION}".endsWith('-SNAPSHOT')) {
                    RELEASE_VERSION = "${VERSION}"
                    BUILD_TYPE = 'snapshot'
                } else if ("${env.BRANCH_NAME}" == 'develop' && "${VERSION}".endsWith('-SNAPSHOT')) {
                    RELEASE_VERSION = "${env.BRANCH_NAME}"
                    BUILD_TYPE = 'snapshot'
                } else if ("${env.BRANCH_NAME}".startsWith('feature') && "${VERSION}".endsWith('-SNAPSHOT')) {
                    RELEASE_VERSION = "${env.BRANCH_NAME}"
                    BUILD_TYPE = 'feature'
                } else if ("${env.BRANCH_NAME}".startsWith('hotfix') && "${VERSION}".endsWith('-SNAPSHOT')) {
                    RELEASE_VERSION = "${env.BRANCH_NAME}"
                    BUILD_TYPE = 'hotfix'
                } else if (isTag && "${env.BRANCH_NAME}".startsWith('release-') && "${VERSION}".endsWith('-SNAPSHOT')) {
                    RELEASE_VERSION = "${env.BRANCH_NAME}".replace("release-", "") + ".RELEASE"
                    BUILD_TYPE = 'release'
                } else if ("${env.BRANCH_NAME}".startsWith('release') && "${VERSION}".endsWith('-SNAPSHOT')) {
                    RELEASE_VERSION = "${VERSION}".replace("-SNAPSHOT", "-RC${currentBuild.number}")
                    BUILD_TYPE = 'releasecandidate'
                } else {
                    error("Your Custom Error for user to see ")
                }

                sh 'mvn --version'
                echo "release version = ${RELEASE_VERSION}"
                sh "mvn versions:set -DnewVersion=${RELEASE_VERSION}"
                sh "mvn clean install" // Can also use sh "mvn clean install -DskipTests" and other similar commands 
            }
        }
    }
    stage("Reports") {
        steps {
            junit allowEmptyResults: true, testResults: 'Your test results metrics location to save test coverage etc results'
            jacoco()
        }
    }
    stage("Archive") {
        steps {
            archiveArtifacts artifacts: '**/target/*.war,**/target/*.jar,**/target/*.zip', fingerprint: true, onlyIfSuccessful: true
        }
    }
}
post {
    always {
        deleteDir() // DO SOME CLEANUP
    }
    success {
        script {
            sendEmail("BUILD STATUS : SUCCESS", "${EMAIL_NOTIFICATION_LIST}", "${APP_NAME}")
        }
    }
    failure {
        script {
            sendEmail("BUILD HAS FAILED", "${EMAIL_NOTIFICATION_LIST}", "${APP_NAME}")
        }
    }
    unstable {
        script {
            sendEmail("BUILD IS NOW UNSTABLE", "${EMAIL_NOTIFICATION_LIST}", "${APP_NAME}")
        }
    }
}
}
def sendEmail(String buildStatus, String recipients, String app) {
buildStatus = buildStatus ?: 'SUCCESSFULLY BUILT'

def scmChanges = getScmChanges()
echo "${scmChanges}"
def subject = "${buildStatus}: ${app} Build: [${env.BUILD_NUMBER}]"
def details = """<p>${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p><p>${scmChanges}</p>"""

emailext (
    to: recipients,
    subject: subject,
    body: details,
    mimeType: 'text/html'
)
}
@NonCPS
def getScmChanges() {
if (currentBuild.changeSets.isEmpty()) {
return 'Looking for new changes if any……………………'
}
def changeLogSets = currentBuild.changeSets

def changeString = ""

for (int a = 0; a < changeLogSets.size(); a++) {
    def entries = changeLogSets[a].items
    for (int b = 0; b < entries.length; b++) {
        def entry = entries[b]
        changeString += "[" + new Date(entry.timestamp) + "][${entry.author}][${entry.commitId}] ${entry.msg}\n"
    }
}
return "Changes: found as below \n" + changeString

}
Note : Not all Pipelines will have these same three stages.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *