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‘   : "\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(‘跳过扫描‘)}
    }

}

  

原文地址:https://www.cnblogs.com/mascot1/p/9964302.html

时间: 2024-10-08 08:11:32

Springboot项目Jenkinsfile模板的相关文章

springboot的thymeleaf模板问题springboot的thymeleaf模板问题

springboot项目引入thymeleaf模板时,默认thymeleaf模板对html5标签是严格检查的.要实现非严格检查 1. 在项目中加NekoHTML库 在Maven中添加依赖 <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> &l

springboot整合Thymeleaf模板引擎

引入依赖 需要引入Spring Boot的Thymeleaf启动器依赖. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>nekohtml</groupId&g

SpringBoot(二)CentOS部署SpringBoot项目从0到1

在之前的博文<详解intellij idea搭建SpringBoot>介绍了idea搭建SpringBoot的详细过程, 并在<CentOS安装Tomcat>中介绍了Tomcat的安装,前面几篇文章实际上已经充分准备好了部署Linux的必要条件.那么今天来看看如何在CentOS部署SpringBoot,让你的SpringBoot在服务器上跑起来. vLinux部署springboot 从0到1,5步走,在Linux Tomcat部署springboot: 1. <CentOS

2springboot:快速创建springboot项目

使用IDEA快速创建springboot项目流程: 创建新的项目选择 项目的命名以及包名 需要什么包就导入什么包 进行测试的单元 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 此

四、创建第一个springboot项目

简介 spring boot 它的设计目的就是为例简化开发,开启了各种自动装配,你不想写各种配置文件,引入相关的依赖就能迅速搭建起一个web工程.它采用的是建立生产就绪的应用程序观点,优先于配置的惯例. 建构准备 jdk 1.8 或以上 maven 3.0+ IntelliJ IDEA 打开Idea-> new Project ->Spring Initializr ->填写group.artifact ->钩上web(开启web功能)->点下一步就行了.创建完工程,工程的目

SpringBoot集成beetl模板快速入门

SpringBoot集成beetl模板快速入门 首次探索 beetl官方网址:http://ibeetl.com/ 创建SpringBoot工程(idea) 新建工程 选择创建Spring工程 书写包名和项目名称等 选择集成web依赖 确认项目保存路径信息 修改maven本地仓库位置 maven本地仓库位置,默认在C盘的: "C:\Users\用户名 ?.m2\repository" 可以复制maven工程下的setting.xml修改其文件,详情见该博客 http://blog.cs

SpringBoot项目启动报错:java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

.   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Sprin

2.springboot:快速创建springboot项目

使用IDEA快速创建springboot项目流程: 创建新的项目选择 项目的命名以及包名 需要什么包就导入什么包 进行测试的单元 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 此

关于springboot项目中自动注入,但是用的时候值为空的BUG

最近想做一些web项目来填充下业余时间,首先想到了使用springboot框架,毕竟方便 快捷 首先:去这里 http://start.spring.io/ 直接构建了一个springboot初始化的项目框架 然后:在页面上选择相应的依赖包,然后点击构建按钮,然后下载并且导入IDE中,目前喜欢使用IDEA 于是一个简答的springboot项目就搭建好了 废话说完,然后想体验下spring中redis的使用: 那就直接新建了一个类,然后 @Autowired 自动注入 RedisTemplate