Springboot项目Jenkinsfile模板

Posted mascot1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot项目Jenkinsfile模板相关的知识,希望对你有一定的参考价值。

Springboot项目Jenkinsfile模板

#!/usr/bin/groovy
import groovy.json.*
import hudson.model.*
//@NonCPS

//代码库信息
String srcUrl = "${env.srcUrl}"
String srcType = "${env.srcType}"
String tagName = "${env.tagName}"
String branchName = "${env.branchName}"
String moduleName = "${env.moduleName}"
String credentialsId = "${env.credentialsId}"

//服务信息
String serviceName = "${env.serviceName}"
String targetHosts = "${env.targetHosts}"
String targetDir = "${env.targetDir}/${serviceName}"
String workspace = "${env.workspace}/${JOB_NAME}"
String activeENV = "${env.activeENV}"  
String user = "${env.user}"
String port = "${env.port}"
String livenessUrl = "${env.livenessUrl}"
String classPath = "${env.classPath}"
String javaOption = "${env.javaOption}"
String startType = "${env.startType}"
String javaVersion = "${env.javaVersion}"
String dependency = "${env.dependency}"
String twoLevelDir = "${env.twoLevelDir}" 

//Jenkins信息
String nodeSlave = "${env.nodeSlave}"
String skipDeploy = "${env.skipDeploy}"
String skipSonar = "${env.skipSonar}"
String buildType = "${env.buildType}"
String buildShell = "${env.buildShell}"
String opsService = "${env.opsService}"
String gitlabCI = "${env.gitlabCI}"
String sonarName = "${JOB_NAME}".split(‘_‘)[0]

//gitlabCI参数
if("${gitlabCI}" != "on" && "${gitlabCI}" != "null"){
    branchName = "${gitlabCI}"
}

//SaltApi信息
String saltUser = "${env.saltUser}"
masters =[testl‘ : "http://127.0.0.1:8000"]
          
hosts = targetHosts.split(‘,‘)
length = hosts.size()

//颜色输出
def PrintMes(value,color){
    colors = [‘red‘   : "33[40;41m >>>>>>>>>>>${value}<<<<<<<<<<< 33[0m",
              ‘green‘ : "33[40;32m >>>>>>>>>>>${value}<<<<<<<<<<< 33[0m" ]
    ansiColor(‘xterm‘) {
        println(colors[color])
    }
}

//saltapi模板
def Salt(salthost,saltfunc,saltargs) {
    String saltCredentialsId = "${env.saltCredentialsId}"
    result = salt(authtype: ‘pam‘, 
                clientInterface: local( arguments: saltargs,
                                        function: saltfunc, 
                                        target: salthost, 
                                        targettype: ‘list‘),
                credentialsId: "${saltUser}", 
                servername: masters["${nodeSlave}"])
    println(result)
    return  result
}

//Json初始化
def JsonInto(value){
    def prettyJson = JsonOutput.prettyPrint(value)
    def jsonSlurper = new JsonSlurper() 
    def jsonSaltresult = jsonSlurper.parseText(prettyJson)
    //println(jsonSaltresult)
    def result 
    for (host in hosts){
        result = jsonSaltresult[0][host]
        println("${host}" + ‘-->‘ + "${result}")
    }
    return result
}

//主机格式化 
def HostInit(targetHosts){
    hostList = [ ]
    if (length < 2){
        String value = hosts[0]
        hostList.add(value)
    } else {
        for (i = 0; i < length-1; i+=2 ){
            String value = hosts[i] + ‘,‘ + hosts[i+1]
            hostList.add(value)
        }
    }
    return hostList
}

//检查主机
def CheckConnect(hosts){
    resulta = Salt(hosts,‘test.ping‘,‘‘)
    result = JsonInto(resulta)
    if (result == true){
        println(hosts + "-->主机连接成功")
    } else{
        println(hosts + "-->主机连接失败")
        error "Host Check Error"
    }
}

//代码检出
def GetCode(srcType,srcUrl,tagName,branchName,credentialsId) {
    if(srcType == "SVN") {
        if(tagName == "null") {
            svnUrl = "${srcUrl}@HEAD"
        }else{
            svnUrl = "${srcUrl}/${tagName}@HEAD"
        }
        checkout([
            $class: ‘SubversionSCM‘, 
            additionalCredentials: [], 
            filterChangelog: false, 
            ignoreDirPropChanges: false, 
            locations: [[credentialsId: "${credentialsId}", 
            depthOption: ‘infinity‘, 
            ignoreExternalsOption: true, 
            remote: "${svnUrl}"]], 
            workspaceUpdater: [$class: ‘CheckoutUpdater‘]]
        ) 
    } else if(srcType == "Git") {
        //delete ‘origin/‘
        if (branchName.startsWith(‘origin/‘)){
        branchName=branchName.minus("origin/")
        } 
        
        if(tagName == "null"){
            pathName = "*/${branchName}"
        }else{
            pathName = "refs/tags/${tagName}"
        }
        checkout([$class: ‘GitSCM‘, branches: [[name: "${pathName}"]], 
            doGenerateSubmoduleConfigurations: false, 
            extensions: [], submoduleCfg: [], 
            userRemoteConfigs: [[credentialsId: "${credentialsId}", 
            url: "${srcUrl}"]]])
    }
}

//build工作目录
def BuildDir(workspace,srcType,tagName,moduleName) {
    def srcDir = workspace
    if(srcType == "Git") {
        buildDir = "${workspace}"
        if(moduleName == "null"){
            srcDir = "${workspace}"
        }else{
            srcDir = "${workspace}/${moduleName}"
        }
    }else{
        if(tagName == "null") {
            def srcTmp = srcUrl.split("/")[-1]
            srcDir = "${workspace}/${srcTmp}"
        }else{
            srcDir = "${workspace}/${tagName}"
        }
        buildDir = srcDir
    }
    return [buildDir,srcDir]
}

//构建 [mvn/ant]
def Build(javaVersion,buildType,buildDir,buildShell){
    if (buildType == ‘maven‘){
        Home = tool ‘M3‘
        buildHome = "${Home}/bin/mvn"
    } else if (buildType == ‘ant‘){
        Home = tool ‘ANT‘
        buildHome = "${Home}/bin/ant"
    } else if (buildType == ‘gradle‘){
        buildHome = ‘/usr/local/bin/gradle‘
    } else{
        error ‘buildType Error [maven|ant|gradle]‘
    }
    echo "BUILD_HOME: ${buildHome}"
    //判断
    if (javaVersion == ‘jdk7‘) {
        println("---USE JDK7---")
        sh """
            export JAVA_HOME=/usr/local/jdk1.7.0_79
            export PATH=$JAVA_HOME/bin:$PATH
            export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
            java -version
            cd ${buildDir} && ${buildHome} ${buildShell}
           """
    } else if (javaVersion == ‘jdk6‘) {
        println("---USE JDK6---")
        sh """
            export JAVA_HOME=/usr/local/jdk1.6.0_45
            export PATH=$JAVA_HOME/bin:$PATH
            export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
            java -version
            cd ${buildDir} && ${buildHome} ${buildShell}
            """
    } else {
        println("---USE JDK8---")
        sh """
            export JAVA_HOME=/usr/java/jdk1.8.0_111
            export PATH=$JAVA_HOME/bin:$PATH
            export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
            java -version

            cd ${buildDir} && ${buildHome} ${buildShell}
        """
    }
    
}

//发布jar包
def DeployPackage(Hosts,JOB_NAME,serviceName,targetDir,user,livenessUrl,srcDir) {
    jarName = sh returnStdout: true, script: "cd ${srcDir}/target;ls *.jar"
    jarName = jarName - ".jar
"
    sh "cp ${srcDir}/target/${jarName}.jar /srv/salt/${JOB_NAME}/${jarName}.jar"
    Salt(Hosts,‘cmd.run‘,"cmd=" mkdir  -p ${targetDir} && chown -R ${user}:${user} ${targetDir}/ "")
    sleep 3;
    Salt(Hosts,‘cp.get_file‘,"salt://${JOB_NAME}/Springboot.sh ${targetDir}/Springboot.sh makedirs=True ")
    sleep 3;
    Salt(Hosts,‘cmd.run‘, "cmd="chmod 755 ${targetDir}/Springboot.sh "")
    sleep 5 ;
    
    //Stop
    ManagerService(Hosts,targetDir,"stop",user)
    
    //Deploy
    try {
        sleep 3;
        Salt(Hosts,‘cmd.run‘,"cmd=" rm ${targetDir}/*.jar -rf "")
        sleep 3;
        Salt(Hosts,‘cp.get_file‘, "salt://${JOB_NAME}/${jarName}.jar ${targetDir}/${jarName}.jar makedirs=True ")
        sleep 5;
        Salt(Hosts,‘cmd.run‘, "cmd=" chown -R ${user}:${user} ${targetDir}/ && chmod 755 ${targetDir}/Springboot.sh "")
    } catch(ERROR) {
        error "***************${Hosts}主机:包部署失败***************" 
    }
    println "发布主机信息:" + ‘  |‘ + "Hosts:" + Hosts + ‘  |‘  + "jarName:" + jarName+ ‘  |‘ +"targetDir:" + targetDir
        
    //Start 
    try{
        sleep 5;
        ManagerService(Hosts,targetDir,"start",user)
        sleep 10;
        ManagerService(Hosts,targetDir,"status",user)
        if(livenessUrl != "null"){
            Salt(Hosts,‘cmd.run‘,"cmd="curl http://127.0.0.1:${port}/${livenessUrl} "")
        }
    } catch(ERROR) {
        currentBuild.result = ‘FAILURE‘
        echo "***************${Hosts}主机服务进程检查失败***************"
    }
}

// 服务启停管理[start|stop|restart]
def ManagerService(Hosts,targetDir,opsService,user) {
        try{
            Salt(Hosts,‘cmd.run‘,"cmd=" cd ${targetDir}/  && ./Springboot.sh  ${opsService}  cd - " runas=${user}")
        } catch(ERROR) {
            error "Caught: ${Hosts}"
        }
    println Hosts + ‘-->>>‘ + opsService + "操作成功"
}

//代码扫描
def SonarScan(skipSonar,srcDir,sonarName){
    if ("${buildType}" == ‘gradle‘){
        classpath = ‘build/classes‘
    } else{
        classpath = ‘target/classes‘
    }
    try {
        def scanHome = tool ‘Scanner2.6‘
        sh """
			    cd ${srcDir} 
			    ${scanHome}/bin/sonar-scanner -Dsonar.projectName=${sonarName} 			    -Dsonar.projectKey=${sonarName}                  -Dsonar.sources=.                  -Dsonar.language=java                 -Dsonar.sourceEncoding=UTF-8                 -Dsonar.java.binaries=${classpath}                 -Dsonar.java.coveragePlugin=jacoco                 -Dsonar.jacoco.reportPath=target/jacoco.exec                 -Dsonar.junit.reportsPath=target/surefire-reports                 -Dsonar.surefire.reportsPath=target/surefire-reports                -Dsonar.projectDescription=‘devopsdevops‘
             """ 

    } catch (e){
    	error ‘skipSonar [false|true] ‘
    }
}

def buildDir = BuildDir(workspace,srcType,tagName,moduleName)[0]  // 获取build工作目录
def srcDir = BuildDir(workspace,srcType,tagName,moduleName)[1]  // 获取build工作目录
arrHosts = HostInit(targetHosts)

// 初始化环境(SpringBoot-nohup)
def Init(javaOption,dependency,length){
    saltWorkspace = "/srv/salt/${JOB_NAME}"
    sh " mkdir ${saltWorkspace} || echo File exists"
    scriptSrc = "http://xxxxxx.com/devops/xxxxx.git"
    //下载脚本
    ws("${saltWorkspace}") {
        GetCode("Git",scriptSrc,"null","master",credentialsId)
        //初始化变量
        sh """
            sed -i "s#activeEnv=#activeEnv=${activeENV}#g" /srv/salt/${JOB_NAME}/Springboot.sh
            sed -i "s#port=null#port=${port}#g" /srv/salt/${JOB_NAME}/Springboot.sh
            """
        if(javaOption != ‘null‘){
            sh """ sed -i "s#javaOption=#javaOption=‘${javaOption}‘#g" /srv/salt/${JOB_NAME}/Springboot.sh """
        }
        
        if(dependency != ‘null‘){
            sh """  sed -i "s#dependency=#dependency=‘${dependency}‘#g" /srv/salt/${JOB_NAME}/Springboot.sh  """
        }
        
        
        if(javaOption.contains(‘eureka‘) == true){
            sh """ sed -i "s#eureka=false#eureka=true#g" /srv/salt/${JOB_NAME}/Springboot.sh """
        }
        if(javaOption.contains(‘active‘) == true){
            sh """ sed -i "s#activeenv=false#activeenv=true#g" /srv/salt/${JOB_NAME}/Springboot.sh """
        }
        
    }
}

// Pipeline
node("${nodeSlave}") {
    //初始化
    PrintMes(‘初始环境‘,‘green‘)
    Init(javaOption,dependency,length)
    
    //检查连接
    PrintMes(‘主机检查‘,‘green‘)
    stage "CheckConnect"  
        CheckConnect(targetHosts)
        
    //判断是有service操作
    if(!"noOperation".equals(opsService)) {
        stage "${opsService} Service"
            ManagerService(targetHosts,targetDir,opsService,user)
    }else {
        ws("${workspace}") {
            def WORKSPACE = pwd()
            echo "WORKSPACE: $WORKSPACE"
            
            //代码检出
            PrintMes(‘代码检出‘,‘green‘)
            stage ‘Checkout‘  
                GetCode(srcType,srcUrl,tagName,branchName,credentialsId)
    
            //构建
            PrintMes(‘执行构建‘,‘green‘)
            stage ‘Build‘
                Build(javaVersion,buildType,buildDir,buildShell)
        }
        
        //发布
        if (skipDeploy == ‘null‘ || skipDeploy == "false"){ 
            PrintMes(‘发布应用‘,‘green‘)
            stage ‘Deploy‘
                if ("${twoLevelDir}" != ‘null‘){
                    srcDir="${srcDir}/${twoLevelDir}"
                }
                for (aHosts in arrHosts){
                    DeployPackage(aHosts,JOB_NAME,serviceName,targetDir,user,livenessUrl,srcDir)
                }
                
        } else {println(‘跳过发布‘)}
           
        //代码扫描
        if (skipSonar == ‘false‘){
            PrintMes(‘代码扫描‘,‘green‘)
            stage ‘Sonar‘
                SonarScan(skipSonar,srcDir,sonarName)
        } else { println(‘跳过扫描‘)}
    }
    
}

  

以上是关于Springboot项目Jenkinsfile模板的主要内容,如果未能解决你的问题,请参考以下文章

Jenkins高级用法 - Jenkinsfile 介绍及实战经验

Docker 容器在手动运行容器时可由 localhost 访问,但在由 jenkinsfile 运行时无法访问

对Jenkinsfile语法说不,开源项目Jenkins Json Build挺你

利用Jenkins Shared Libraries隐藏你的Jenkinsfile

SpringBoot项目配置模板(SpringBoot + MybatisPlus + Druid)

SpringBoot IDEA 搭建 springboot 项目 + jsp 页面模板