Springboot專案Jenkinsfile模板
阿新 • • 發佈:2018-11-15
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' : "\033[40;41m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m", 'green' : "\033[40;32m >>>>>>>>>>>${value}<<<<<<<<<<< \033[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\n" 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('跳過掃描')} } }