Jenkins&Gitlab:jenkins构建成功后在gitlab打tag

插件?

首先想找找jenkins有没有合适的插件:

  • git publisher长时间无人维护;
  • git push 并不适合目前的多分支流水线构建。
    此路不通。

    api

那只能走gitlab-doc这条路了。

  1. 创建gitlab token, setting->access tokens,创建个人token,确保有访问构建的项目权限。
    token

  2. jenkins 安装 http request插件,创建全局凭据,类型切记选择secret text,不要选gitlab api token.
    凭据

  3. 在share library jenkins-library 创建目录src/com/xzlcorp,创建文件gitlab.groovy.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
       package com.xzlcorp

    //封装HTTP请求
    def HttpReq(reqType,reqUrl,reqBody){
    def gitServer = "https://git.xzlcorp.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
    }

    //创建tag
    def CreateTag(projectId, tag, branchName){
    def apiUrl = "projects/${projectId}/repository/tags"
    reqBody = """{"tag_name": "${tag}","ref":"${branchName}", "message": "${branchName}"}"""
    response = HttpReq('POST',apiUrl,reqBody)
    println(response)
    }
  1. 在项目的jenkinsfile中加入代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    @Library('jenkins-libs-web@master') _

    def gitlab = new com.xzlcorp.gitlab()
    def tool = new com.xzlcorp.tools()

    String projectName = "project-name"

    pipiline {
    ...
    post {
    always {
    // echo "构建结束"
    }

    success {
    // echo "构建成功"
    script {
    if (env.BRANCH == "master") {
    projectId = gitlab.GetProjectID(projectName)
    tool.PrintMsg("打tag start","blue")
    String tagString = "v${new Date().format("yy.MMdd.HHmm")}"
    gitlab.CreateTag(projectId, tagString, env.BRANCH_NAME)
    tool.PrintMsg("打tag end","blue")
    }
    }
    }

    failure {
    echo "构建失败"
    }

    aborted {
    echo "构建中断"
    }
    }
    }
分享到 评论