在使用Jenkins时经常需要通过http请求去操作service API。有几种办法可以实现,简单的两种包括通过curl命令和HTTP Request Plugin插件。今天介绍HTTP Request Plugin插件的使用。
HTTP Request Plugin插件地址

在pipeline中使用参照这两个文档

https://github.com/jenkinsci/http-request-plugin
https://www.jenkins.io/doc/pipeline/steps/http_request/

配合sharedlibraries使用

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

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐