2-1. jenkins pipeline脚本组织构建步骤(完整脚本及案例job配置)

“ jenkins pipeline脚本组织构建步骤”中完整的脚本和job配置案例

pipeline脚本


pipeline{

    agent any

    options{

        retry(1)

    }

    

// parameters {

     // 等价于UI界面配置:This project is parameterized

// string(name: 'DEPLOY_DIR', defaultValue: '/app/rpcusr/auto_deploy', trim: true, description: '部署服务器上执行拉包脚本的目录')

// string(name: 'DEPLOY_TARGET_DOCUMENTS', defaultValue: '', trim: true, description: '部署服务器上jar包拉取的目标地址~/apphome/[值],若不配置默认目标地址将为lib')

// booleanParam(defaultValue: false, description: '手动构建时,是否进行部署', name: 'DEPLOY')

        

        // 参数说明:

  // gitl_url 目标git地址

  // gitl_branch 目标git分支

  // gitl_user 操作git的用户,提前在Credentials中配置userName和password凭据 

  // build_child_dir 指定编译的git项目子目录,默认为git项目根目录

  // build_mvn_opt 指定maven编译命令

  // DEPLOY 是否执行部署步骤(手动构建以此为准)

  // HOOK_DEPLOY 是否允许hook触发部署(hook构建以此为准)

  // DEPLOY_HOST 部署操作的远程主机

  // DEPLOY_USER 部署操作的用户,提前在Credentials中配置userName和password凭据 

  // DEPLOY_DIR 远程主机中部署脚本的位置

  // DEPLOY_TARGET_DOCUMENTS 部署服务器上jar包拉取到的目标地址,默认为lib,~/apphome/${DEPLOY_TARGET_DOCUMENTS}

        

// }

    

    environment {

     // 自定义配置

     gitl_url = "$gitl_url"

        gitl_user = "$gitl_user"

        gitl_branch = "$gitl_branch"

        build_child_dir = "$build_child_dir"

        

    

  // 其他

        workspace = pwd()

        codedir = "code"

        mvnHome = "$MAVEN_HOME"

        jdkHome = "$JAVA_HOME"

        

        PATH = "${JAVA_HOME}/bin:${MAVEN_HOME}/bin:${PATH}"

    }

    

    post {

          //写相关post部分代码

        always {

            script {

                echo "post:always-------------"

            }

        }

        changed {

            script {

                echo "post:changed-------------状态有变化?"

            }

        }

        failure {

            script {

                echo "post:failure-------------失败了?发邮件?"

            }

        }

        success {

            script {

                echo "post:success-------------成功了?发邮件?"

            }

        }

    }

    



    stages{

        stage('HookConfig') { 

            steps{

                script{

                 //if(!githook_object_kind.trim().isEmpty() && githook_object_kind.trim() != 'null'){

     if (env.githook_object_kind != null && !env.githook_object_kind.trim().isEmpty()) {

                  echo "本次构建由hook触发"

                  

                  // gitlabhook 相关配置信息,依赖Generic Webhook Trigger插件配置Post content parameters [Variable:githook, Expression:$]

            githook_ref = "$githook_ref" // refs/heads/master

            githook_repository_name = "$githook_repository_name"	// spring-boot-parent-hzw

            githook_object_kind = "$githook_object_kind"

            

                     // 检查hook触发的项目名和该job目标git路径是否匹配

                     if (!gitl_url.matches(".*/" + githook_repository_name + ".git")){

                         error "目标项目${githook_repository_name}无法匹配目标地址${gitl_url}"

                     }

                     

                     def ref_list = githook_ref.tokenize('/')

                     def ref_type = ref_list[1]	// heads、tags

                     def ref_name = ref_list[2]	// master、v0.1

                     

                     // 设置hook中分支名

                     gitl_branch = ref_name

                     

                     

                     if(env.HOOK_DEPLOY == "true"){

                      echo "HOOK_DEPLOY is true, will deploy whith hook!"

                      env.DEPLOY="true"

                     }else{

                      echo "HOOK_DEPLOY is false, will not deploy whith hook!"

                      env.DEPLOY="false"

                     }

                     

                 }else{

                  echo "本次构建非hook触发"

                 }

                }

            }

        }

        

        stage('InitConfig'){

         steps{

          script{

                 

           println("构建参数信息:"

           + "\ngitl_url :" + env.gitl_url               

           + "\ngitl_branch :" + env.gitl_branch            

           + "\nbuild_child_dir :" + env.build_child_dir        

           + "\nbuild_mvn_opt :" + env.build_mvn_opt          

           + "\nDEPLOY :" + env.DEPLOY                 

           + "\nDEPLOY_HOST :" + env.DEPLOY_HOST            

           + "\nDEPLOY_USER :" + env.DEPLOY_USER            

           + "\nDEPLOY_DIR :" + env.DEPLOY_DIR             

           + "\nDEPLOY_TARGET_DOCUMENTS:" + env.DEPLOY_TARGET_DOCUMENTS

           )

          }

         }

        }

        

        stage('CodeCheck') {

            steps{

                // git branch: "master", credentialsId: 'd87b6196-bae0-4195-88d6-7f85d76f52b1', url: 'http://172.27.0.2/gitlabtest/spring-boot-parent-hzw.git'

                script{

                    url="${gitl_url}"

                    branch="${gitl_branch}" // 目标分支也可以是tag号

                    credentialsId="${gitl_user}"

                    

                    echo "=checkout url:${url} branch:${branch}="

                }

             

                checkout([

                    $class: 'GitSCM', 

                    branches: [[name: "$branch"]], 

                    doGenerateSubmoduleConfigurations: false, 

                    extensions: [

                        [$class: 'CleanBeforeCheckout'], 

                        [$class: 'RelativeTargetDirectory', relativeTargetDir: "$codedir"], 

                        [$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', timeout: 3, trackingSubmodules: false]

                    ], 

                    submoduleCfg: [], 

                    userRemoteConfigs: [

                        [credentialsId: "$credentialsId", url: "$url"]

                    ]

                ]) 

            }

        }

        

        stage('Build') {

            steps{

             script{

              echo "开始构建..."

     builddir="${workspace}/${codedir}"

     

     if (env.build_child_dir != null && !env.build_child_dir.trim().isEmpty() && env.build_child_dir.trim()!='null') {

      echo "已配置构建子目录:${build_child_dir}"

      builddir="${builddir}/${build_child_dir}"

     }

     

     if (env.build_mvn_opt != null && !env.build_mvn_opt.trim().isEmpty() && env.build_mvn_opt.trim()!='null') {

      echo "已配置构建指令:${build_mvn_opt}"

      build_mvn_opt="${build_mvn_opt}"

     }else{

      echo "未配置构建指令,使用默认指令:clean install"

      build_mvn_opt="clean install"

     }

     

     echo "构建目录为:${builddir},构建指令:${build_mvn_opt}"

     

             }

    

             // maven构建生成二进制包

                dir("${builddir}"){

              // 此处需jenkins安装插件:Pipeline Maven Integration

              withMaven(

              //	options: [pipelineGraphPublisher(disabled: true)] // 禁用依赖构建下游job??

              ) {

                  //sh "mvn clean deploy -Dmaven.test.skip=true"

                  sh "mvn ${build_mvn_opt}"

           }

           

           

                }

                

            }

        }

        

        

        stage('Deploy') {

         when {

       expression {

           return (env.DEPLOY == "true")

       }

   }

            steps {

                script {

                 echo "开始部署......"

                

                 jobsdir="${JENKINS_HOME}/jobs/${currentBuild.projectName}/builds/${currentBuild.id}/archive"

                 dir("${jobsdir}"){

                     def files = findFiles(glob: '**/*.jar')

                     

                     def archiveMsg=""

                     

                     for(jarfile in files){

                      if(jarfile.path.endsWith("sources.jar")) continue

                      def pomfile=jarfile.path.substring(0, jarfile.path.lastIndexOf(".")) + ".pom"

                      archiveMsg += sh(script: "echo 'jenkins \${project.groupId} \${project.artifactId} \${project.version}'| mvn -DforceStdout help:evaluate -f ${jobsdir}/${pomfile} | grep 'jenkins' |sed 's/jenkins\\s*//g'",returnStdout: true).trim() + "\n"

                      //archiveMsg += sh(script: "echo '\${project.groupId} \${project.artifactId} \${project.version}'| mvn -q -DforceStdout help:evaluate -f ${jobsdir}/${pomfile}",returnStdout: true).trim() + "\n"

                      //archiveMsg += sh(script: "echo '\${project.groupId} \${project.artifactId} \${project.version}'| mvn -q -DforceStdout org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate -f ${jobsdir}/${pomfile}",returnStdout: true).trim() + "\n"

                      

                     }

                        // TODO过滤出需要拉包的id



                     echo "========\n${archiveMsg}\n========"

                     remote = [:]

                  remote.name='xxxx'

                  remote.host=env.DEPLOY_HOST

                  remote.allowAnyHosts= true

                  //remote.pty=true

                  

                  withCredentials([usernamePassword(credentialsId: env.DEPLOY_USER, passwordVariable: 'password', usernameVariable: 'userName')]) {

                   remote.user=userName

                   remote.password=password

                  }

                     

                     // 这里生成的文件头增加声明#!/bin/bash --login ,确保执行脚本时环境变量的完整

                     writeFile file:"deploy-${currentBuild.projectName}.sh", text: "#!/bin/bash --login\n cd ${DEPLOY_DIR} \n echo \"${archiveMsg}\" > jenkinslist\$\$.temp \n bash pkJenkins.sh -f jenkinslist\$\$.temp -d \"${DEPLOY_TARGET_DOCUMENTS}\" \n rm jenkinslist\$\$.temp"

                     

                     sshScript remote: remote,script: "deploy-${currentBuild.projectName}.sh"

                     

                 }

                }

            }

        }



    }

   

}

完整的样例job配置

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hzw@sirius

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值