zoukankan      html  css  js  c++  java
  • Jenkins与版本管理系统gitlab对接

    提交流水线

    当Gitlab中触发push操作,则触发相对应的Jenkins流水线构建。实现快速反馈与验证。

    方式1: 使用Gitlab CI,当有push请求,在CI脚本中远程触发Jenkins项目构建。

    需要准备Gitlab runner

    编写触发Jenkins脚

    方式2: 使用Gitlab WebHook,当有push请求,直接触发jenkins项目构建。【采用】

    需要配置Gitlab webHook

    需要配置Jenkins项目Hook

    推荐使用Generic Webhook Trigger触发器,需要安装插件

    1)安装插件

     2)开启Generic Webhook Trigger

    添加一个请求参数runOpts Request parameters ,用于辨别手动触发构建与提交构建

    配置一个token默认我使用的是项目的名称,必须唯一,否则在配置了相同的token的项目都会被触发

    Print post content用于展示请求日志,Print contributed variables展示我们在post中获取的变量内容

     3)配置gitlab

    我们找到要配置提交触发构建的项目,设置->集成,勾选Push Events

     配置完成,这时候我们进行提交代码,会发现已经能够正常触发项目构建了。如果出现了问题,我们重点检查jenkins的项目触发URL和网络权限问题

    二)提交流水线优化

    1)分支名称自动替换、增加构建描述信息

    当我们在任意分支提交的时候,Jenkins需要获取我们提交的分支进行构建,而不是固定的分支

    增加获取hook参数

     编写sharelibrary中的Jenkinsfile文件

    if ("${runOpts}" == "GitlabPush"){
        env.runOpts = "GitlabPush"
        branchName = branchName - "refs/heads/"
        currentBuild.description = "Trigger by ${userName} ${branch}"
    }
    

      

    测试

    2)变更commit状态

    如何添加这个凭据?

    操作方法: 1. 在Gitlab中新建一个token, 系统设置 -> access token 2. 在Jenkins 新建凭据 -> 选择凭据类型secure text -> 填写凭据id(可以自定义)-> 填写gitlab的token。

     

    https://docs.gitlab.com/ee/api/commits.html#post-the-build-status-to-a-commit

     关于gitlab中pipeline的状态有:[pending, running, success, failed, canceled] 。 接口地址为projects/${projectId}/statuses/${commitSha}?state=state

     s

     共享库创建一个文件src/org/devops/gitlab.groovy

    package org.devops
    
    //封装HTTP请求
    def HttpReq(reqType,reqUrl,reqBody){
        def gitServer = "http://gitlab.aa.com/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
    }
    

    配置jenkinsfile文件

    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")
         }
       }
      }
    }
    
            
    

      

    测试

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

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

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

     Expression: ^pushs(?!0{40}).{40}s(?!0{40}).{40}srefs/heads/(dev|test|beta)$

    Text:  $object_kind $before $after $branch

    4)合并流水线

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

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

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

     5)构建失败邮件通知

    安装插件

    首先要为每个开发人员分配一个邮箱,并且要在Gitlab中填写好。登录个人用户进行配置哦

     

    邮件通知的功能很重要,我们要为每条流水线都加上这个步骤,我们在共享库中封装一个toemail.groovy。 新建文件src/org/devops/toemail.groovy。在这个文件中,我们写了一段HTML代码,主要展示Jenkins的构建信息

    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.1.200:8080/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    
    }
    

    Jenkins需要配置邮件通知,安装插件Email Extension,然后进入系统管理-> 系统设置 ->Extended E-email Notification

    这里我使用的是163邮箱,填写SMTP服务器地址smtp.163.com 和端口 465注意要开启SSL,密码为授权码。

     在流水线中引用

    def toemail = new org.devops.toemail()
    
    
    
            success{
                script{
                    println("success")
                    gitlab.ChangeCommitStatus(projectId,commitSha,"success")
                    toemail.Email("流水线构建成功",userEmail)
                }
            
            }
            failure{
                script{
                    println("failure")
                    gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
                    toemail.Email("流水线构建失败",userEmail)
                }
            }
            
    

      

  • 相关阅读:
    【MongoDB】windows平台搭建Mongo数据库复制集(相似集群)(一)
    关于jave在oracle驱动下事务提交与回滚问题
    将其它图片格式转为.eps格式
    学习OpenBlas
    ZOJ3640-Help Me Escape
    向死而生——我修的死亡学分
    iOS对象属性详解
    http状态码介绍
    8080端口被占用
    图片特效
  • 原文地址:https://www.cnblogs.com/louis2008/p/jenkins-gitlab.html
Copyright © 2011-2022 走看看