jenkins笔记之pipeline

现场情况:

1. 各项目模块下子项目结构不同

2. maven构建每次只能全局构建, 不能单独模块进行构建

实现目标:

1. 选择模块后动态弹出子项目, 供勾选发布或重启

2. 参数化配置界面可选择此次发布是否进行构建

3. 动态获取GIT分支, 供勾选

最终效果图:

 

 

active choice界面化配置大概是这样:

groovy代码

return [
"credit-business",
"credit-support",
"credit-interface-converter",
"credit-gateway"
]

 groovy代码

if (project.equals("credit-business")) {
    return ["business-account:selected","business-manage","business-credit","business-loan"]
} else if (project.equals("credit-support")) {
    return ["credit-cache-manage:selected","credit-rule-manage","credit-workflow","credit-uaa","credit-database-synchronize"]
} else if (project.equals("credit-interface-converter")) {
    return ["credit-interface-converter:selected"]
} else if (project.equals("credit-gateway")) {
    return ["credit-gateway:selected"]
} else {
    return ["Unknown hosts"]
}

 

 此步骤重点在于两次参数选项的关联, 即Referenced parameters选项的参数, 使project和subprojects关联起来

pipeline脚本如下:

// Plugins: Git plugin, Pipeline, Extended Choice Parameter, Active Choice Parameter, Publish Over SSH, Maven Integration, SonarQube Scanner for Jenkins, LDAP Plugin, Role-based Authorization, Authorize Project, Git Parameter, Workspace Cleanup Plugin, Conditional BuildStep
properties([
    parameters([
        [$class: 'ChoiceParameter', choiceType: 'PT_SINGLE_SELECT', 
        description: '必选项: 请选择要操作的项目名称', filterLength: 1, 
        filterable: false, name: 'project', 
        randomName: 'choice-parameter-16477448705762715', 
        script: [
            $class: 'GroovyScript', 
            fallbackScript: 
                [classpath: [], sandbox: false, 
                script: 'return ["Envrionment Undefined"]'
                ], 
            script: 
                [classpath: [], sandbox: false, 
                script: 'return ["credit-business","credit-support","credit-interface-converter","credit-gateway"]'
                ]
            ]
        ], 
        [$class: 'CascadeChoiceParameter', choiceType: 'PT_CHECKBOX', 
        description: '必选项: 请勾选需要操作的子项目', filterLength: 1, filterable: false, name: 'subprojects', 
        randomName: 'choice-parameter-16477448709149855', referencedParameters: 'project', 
        script: [
            $class: 'GroovyScript', 
            fallbackScript: 
                [classpath: [], sandbox: false, 
                script: 'return ["Envrionment Undefined"]'
                ], 
            script: [
                classpath: [], sandbox: false, 
                script: '''
                    if (project.equals("credit-business")) {
                        return ["business-account:selected","business-manage","business-credit","business-loan"]
                    } else if (project.equals("credit-support")) {
                        return ["credit-cache-manage:selected","credit-rule-manage","credit-workflow","credit-uaa","credit-database-synchronize"]
                    } else if (project.equals("credit-interface-converter")) {
                        return ["credit-interface-converter:selected"]
                    } else if (project.equals("credit-gateway")) {
                        return ["credit-gateway:selected"]
                    } else {
                        return ["Unknown hosts"]
                    }
                    '''
                ]
            ]
        ]
    ])
])
pipeline {
    agent any
    tools {
        maven 'MAVEN3'
        jdk 'JDK1.8'
    }
    options {
      buildDiscarder logRotator(
      daysToKeepStr: '', 
      numToKeepStr: '10')
    }
    environment {
        // 项目代码拉取
        git_path = "http://3.1.101.38:8098/credit-rebuild/bank-credit-sy.git"
        git_auth_id = "cfa69b9a-5c02-4992-b09a-6dd4e757700c"
        }
    parameters {
        choice choices: ['Deploy', 'Restart'], 
        description: '必选项: 选择发布项目或者重启服务', 
        name: 'Action'
        
        gitParameter branch: '', branchFilter: '.*', 
        defaultValue: '*/master', description: '发布选项: 请选择GIT分支', 
        name: 'git_branch', quickFilterEnabled: false, 
        selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', 
        type: 'PT_BRANCH'
        
        extendedChoice defaultValue: 'Yes', description: '发布选项: 是否进行全新的Maven构建;  一次提交,多次发版,可跳过构建节省时间', 
        descriptionPropertyValue: '进行Maven构建并发版,清除Maven缓存全新构建,跳过Maven构建直接发版', multiSelectDelimiter: ',', 
        name: 'MavenBuild', quoteValue: false, saveJSONParameterToFile: false, 
        type: 'PT_RADIO', value: 'Yes,Clean,No', 
        visibleItemCount: 5
    }
    stages {
        stage('项目代码拉取') {
            steps {
                script {
                    if ( env.Action == "Deploy" && env.MavenBuild == "Clean" ) {
                        deleteDir()  // clean up current workspace
                        checkout([$class: 'GitSCM', branches: [[name: "${git_branch}"]], extensions: [], 
                        userRemoteConfigs: [[credentialsId: "${git_auth_id}", url: "${git_path}"]]])
                    }
                    else {
                        checkout([$class: 'GitSCM', branches: [[name: "${git_branch}"]], extensions: [], 
                        userRemoteConfigs: [[credentialsId: "${git_auth_id}", url: "${git_path}"]]])
                    }
                }
            }
        }
        stage('代码质量检查'){
            when {
              anyOf {
                  allOf {
                    environment name: 'Action', value: 'Deploy'
                    environment name: 'MavenBuild', value: 'Yes'
                  }
                  allOf {
                    environment name: 'Action', value: 'Deploy'
                    environment name: 'MavenBuild', value: 'Clean'
                  }
              }
            }
            steps{
                script {
                    // SonarQubeScanner为全局变量配置的名称
                    ScannerHome = tool 'SonarQubeScanner'
                    // SonarQubeServer为系统配置中配置的名称
                    withSonarQubeEnv('SonarQubeServer') {
                    sh """
                    cd $project
                    ${ScannerHome}/bin/sonar-scanner -Dsonar.projectKey="$project" -Dsonar.projectName="$project"
                    """
                    }
                }
            }
        }
        stage('项目构建') {
            when {
              anyOf {
                  allOf {
                    environment name: 'Action', value: 'Deploy'
                    environment name: 'MavenBuild', value: 'Yes'
                  }
                  allOf {
                    environment name: 'Action', value: 'Deploy'
                    environment name: 'MavenBuild', value: 'Clean'
                  }
              }
            }
            steps {
                script {
                    if ( env.MavenBuild == "Clean" ) {
                        sh "rm -rf /root/.m2"
                        withMaven(jdk: 'JDK1.8', maven: 'MAVEN3') {
                        sh '''
                        java -version
                        mvn -version
                        mvn clean install -Dmaven.test.skip=true
                        '''
                        }
                    }
                    else {
                    withMaven(jdk: 'JDK1.8', maven: 'MAVEN3') {
                        sh '''
                        java -version
                        mvn -version
                        mvn clean install -Dmaven.test.skip=true
                        '''
                        }
                    }
                }
            }
        }
        stage('项目发布') {
            when {
                environment name: 'Action', value: 'Deploy'
            }
            steps {
                script {
                    def remove_prefix = ""
                    def remote_server = "weblogic1"
                    def remote_path = "/opt/ccms-auto-deploy"
                    def remote_dir = ""
                    if ( env.project == "credit-support" || env.project == "credit-business" ) {
                        for (subproject in subprojects.tokenize(',')) {
                            // 项目代码发布
                            def target_dir = "${project}/${subproject}/*-server/target"
                            def target_file = "*.jar"
                            def source_file = "${target_dir}/${target_file}"
                            def remote_cmd = "cd ${remote_path}/${target_dir}; ps aux |grep `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1`|grep -v grep|awk '{print \$2}'|xargs kill -9; source /etc/profile; nohup java -jar -Dspring.profiles.active=test -javaagent:/opt/skywalking/agent/skywalking-agent.jar -Dskywalking.agent.service_name=${subproject}  `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1` >> ${subproject}.log &"
                            sshPublisher(publishers: [sshPublisherDesc(configName: "${remote_server}", 
                            transfers: [sshTransfer(execCommand: "${remote_cmd}", 
                            remoteDirectory: "${remote_dir}", removePrefix: "${remove_prefix}", sourceFiles: "${source_file}")],)])
                        }
                    }
                    if ( env.project == "credit-interface-converter" ) {
                        // 项目代码发布
                        def target_dir = "${project}/*-server/target"
                        def target_file = "*.jar"
                        def source_file = "${target_dir}/${target_file}"
                        def remote_cmd = "cd ${remote_path}/${target_dir}; ps aux |grep `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1`|grep -v grep|awk '{print \$2}'|xargs kill -9; source /etc/profile; nohup java -jar -Dspring.profiles.active=test -javaagent:/opt/skywalking/agent/skywalking-agent.jar -Dskywalking.agent.service_name=${project}  `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1` >> ${project}.log &"
                        sshPublisher(publishers: [sshPublisherDesc(configName: "${remote_server}", 
                        transfers: [sshTransfer(execCommand: "${remote_cmd}", 
                        remoteDirectory: "${remote_dir}", removePrefix: "${remove_prefix}", sourceFiles: "${source_file}")],)])
                    }
                    if ( env.project == "credit-gateway" ) {
                        // 项目代码发布
                        def target_dir = "${project}/target"
                        def target_file = "*.jar"
                        def source_file = "${target_dir}/${target_file}"
                        def remote_cmd = "cd ${remote_path}/${target_dir}; ps aux |grep `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1`|grep -v grep|awk '{print \$2}'|xargs kill -9; source /etc/profile; nohup java -jar -Dspring.profiles.active=test -javaagent:/opt/skywalking/agent/skywalking-agent.jar -Dskywalking.agent.service_name=${project}  `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1` >> ${project}.log &"
                        sshPublisher(publishers: [sshPublisherDesc(configName: "${remote_server}", 
                        transfers: [sshTransfer(execCommand: "${remote_cmd}", 
                        remoteDirectory: "${remote_dir}", removePrefix: "${remove_prefix}", sourceFiles: "${source_file}")],)])
                    }
                }
            }
        }
        stage('项目重启') {
            when { environment name: 'Action', value: 'Restart' }
            steps {
                script {
                    def remote_server = "weblogic1"
                    def remote_path = "/opt/ccms-auto-deploy"
                    if ( env.project == "credit-support" || env.project == "credit-business" ) {
                        for (subproject in subprojects.tokenize(',')) {
                            // 项目代码发布
                            def target_dir = "${project}/${subproject}/*-server/target"
                            def remote_cmd = "cd ${remote_path}/${target_dir}; ps aux |grep `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1`|grep -v grep|awk '{print \$2}'|xargs kill -9; source /etc/profile; nohup java -jar -Dspring.profiles.active=test -javaagent:/opt/skywalking/agent/skywalking-agent.jar -Dskywalking.agent.service_name=${subproject}  `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1` >> ${subproject}.log &"
                            sshPublisher(publishers: [sshPublisherDesc(configName: "${remote_server}", 
                            transfers: [sshTransfer(execCommand: "${remote_cmd}")],)])
                        }
                    }
                    if ( env.project == "credit-interface-converter" ) {
                        // 项目代码发布
                        def target_dir = "${project}/*-server/target"
                        def remote_cmd = "cd ${remote_path}/${target_dir}; ps aux |grep `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1`|grep -v grep|awk '{print \$2}'|xargs kill -9; source /etc/profile; nohup java -jar -Dspring.profiles.active=test -javaagent:/opt/skywalking/agent/skywalking-agent.jar -Dskywalking.agent.service_name=${project}  `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1` >> ${project}.log &"
                        sshPublisher(publishers: [sshPublisherDesc(configName: "${remote_server}", 
                        transfers: [sshTransfer(execCommand: "${remote_cmd}")],)])
                    }
                    if ( env.project == "credit-gateway" ) {
                        // 项目代码发布
                        def target_dir = "${project}/target"
                        def remote_cmd = "cd ${remote_path}/${target_dir}; ps aux |grep `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1`|grep -v grep|awk '{print \$2}'|xargs kill -9; source /etc/profile; nohup java -jar -Dspring.profiles.active=test -javaagent:/opt/skywalking/agent/skywalking-agent.jar -Dskywalking.agent.service_name=${project}  `cd ${remote_path}/${target_dir}/;ls -1t *.jar|head -n1` >> ${project}.log &"
                        sshPublisher(publishers: [sshPublisherDesc(configName: "${remote_server}", 
                        transfers: [sshTransfer(execCommand: "${remote_cmd}")],)])
                    }
                }
            }
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值