Jenkins提交流水线优化

前言

gitlab通过webhook实现代码提交时自动触发jenkins流水线构建(见上一节https://www.cnblogs.com/wuxinchun/p/16795954.html

当gitlab自动触发,是以post请求触发jenkins任务,jenkins任务可以从post请求中获取相应参数供构建使用,如下:

 

 json解析后

故:可以从JSON中获取相应参数,供后续任务构建使用

 

1.获取分支名称

1)配置Post content parameters,获取请求参数

2)修改jenkinsfile获取参数

 

2.增加构建描述信息

1)获取用户名

 2)jenkinsfile增加 currentBuild.description

 3)触发构建

 

3.变更gitlab每次提交后commit状态

思路:通过jenkins流水线获取执行过程(running)或执行结束(success,failed,cancle)等状态,调用gitlab api(封装httprequest请求)来修改本次代码提交状态

1)安装HTTP Request插件

2)创建gitlab-token访问令牌

3) jenkins添加凭证(secreat text类型)

4)gitlab.groovy封装http请求

package org.devops

//封装HTTP请求
def HttpReq(reqType,reqUrl,reqBody){
    def gitServer = "http://192.168.164.158/api/v4"
    withCredentials([string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
      result = httpRequest customHeaders: [[maskValue: true, name: 'PRIVATE-TOKEN', value: "${gitlabToken}"]], 
                httpMode: reqType, 
                contentType: "APPLICATION_JSON",
                consoleLogResponseBody: true,
                ignoreSslErrors: true, 
                requestBody: reqBody,
                url: "${gitServer}/${reqUrl}"
                //quiet: true
    }
    return result
}



//更改提交状态
def ChangeCommitStatus(projectId,commitSha,status){
    commitApi = "projects/${projectId}/statuses/${commitSha}?state=${status}"
    response = HttpReq('POST',commitApi,'')
    println(response)
    return response
}

5)jenkinsfile中调用gitlab.groovy共享库

def gitlab = new org.devops.gitlab()
 
if ("${runOpts}" == "GitlabPush"){
    env.runOpts = "GitlabPush"
    branchName = branch - "refs/heads/"
    currentBuild.description = "Trigger by ${userName} ${branch}"
    gitlab.ChangeCommitStatus(projectId,commitSha,"running")
}
 
post {
    always{
       script{
          println("always")
        }
    }
 
    success{
       script{
          println("success")
          gitlab.ChangeCommitStatus(projectId,commitSha,"success")
        }
      }
    failure{
     script{
        println("failure")
        gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
      }
    }
   aborted{
     script{
        println("aborted")
         gitlab.ChangeCommitStatus(projectId,commitSha,"canceled")
     }
   }
  }
}

6)添加projectid和commitSha变量(用于ChangeCommitStatus函数传参使用)

 

7)测试验证

 

4.过滤特殊push请求,指定分支push触发构建

实现:创建分支不触发流水线请求

参考官方的说明:https://github.com/jenkinsci/generic-webhook-trigger-plugin/tree/master/src/test/resources/org/jenkinsci/plugins/gwt/bdd

1)Api参考

 

2)添加三个变量,获取当前的提交信息 $object_kind $before $after

3)配置过滤条件

Expression: ^push\s(?!0{40}).{40}\s(?!0{40}).{40}$

Text:  $object_kind $before $after

 

 

 

5.合并流水线

关于合并流水线的配置之前要把提交流水线配置好,当提交流水线配置好了,合并流水线只需要修改一个配置。

当流水线成功后才可以合并:会检查原分支中的最后一次提交的状态是否为success

 当原分支最后一次提交的状态为success,则可以合并,只有流水线成功后,才可以合并代码

 

6.构建失败邮件通知

1)安装Email extension插件 

2)gitlab修改提交用户(root)对应邮箱

 3)toemail.groovy

package org.devops

//定义邮件内容
def Email(status,emailUser){
    emailext body: """
            <!DOCTYPE html> 
            <html> 
            <head> 
            <meta charset="UTF-8"> 
            </head> 
            <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0"> 
                <img src="http://192.168.164.158/static/0eef74bf/images/headshot.png">
                <table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">   
                    <tr> 
                        <td><br /> 
                            <b><font color="#0B610B">构建信息</font></b> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td> 
                            <ul> 
                                <li>项目名称:${JOB_NAME}</li>         
                                <li>构建编号:${BUILD_ID}</li> 
                                <li>构建状态: ${status} </li>                         
                                <li>项目地址:<a href="${BUILD_URL}">${BUILD_URL}</a></li>    
                                <li>构建日志:<a href="${BUILD_URL}console">${BUILD_URL}console</a></li> 
                            </ul> 
                        </td> 
                    </tr> 
                    <tr>  
                </table> 
            </body> 
            </html>  """,
            subject: "Jenkins-${JOB_NAME}项目构建信息 ",
            to: emailUser
        
}

4)jenkinsfile调用

def toemail = new org.devops.toemail()
post{
        always{
           script{
           println("always")
           }    
    }
        success{
           script{
            println("success")
            gitlab.ChangeCommitStatus(projectId,commitSha,"success")
            toemail.Email("流水线成功",userEmail)
           }
    }
        failure{
           script{
           println("failure")
           gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
           toemail.Email("流水线失败",userEmail)
           }
        }
        aborted{
           script{
           println("aborted")
           gitlab.ChangeCommitStatus(projectId,commitSha,"canceled")
           toemail.Email("流水线取消",userEmail)
           }
        }
    }

 5)qq邮箱生成授权码

6)jenkins配置邮箱信息

 

7)构建测试验证

 

posted @ 2022-10-16 18:39  杰宏唯一  阅读(287)  评论(0编辑  收藏  举报