简体   繁体   中英

Accessing GitLab JSON from Jenkins Groovy script

In the project I'm working on, we use GitLab CE along with Jenkins for CI.

Currently we merge changes using Jenkins job by just passing branch name as an input parameter. I want to create a job which takes merge request ID (eg 123) and uses GitLab URL API to get info such as eg source branch, target branch etc. and then does the rest (build, merge).

I'm a total beginner (both to Jenkins and Groovy) and what I did is just:

// Removing whitespace from input parameter
def mergeRequest = MergeRequestID
mergeRequest = mergeRequest.replaceAll("\\s","")

// Obtaining JSON with merge request information, 13 is an ID of the project
def apiURL = new URL("https://example.com/api/v4/projects/13/merge_requests/" + mergeRequest)
List json = new JsonSlurper().parse(apiUrl.newReader())

// Here: check for upvotes/downvotes, discussions or anything else. 
assert json.upvotes >= 2  : "Request should have at least 2 upvotes"
assert json.downvotes == 0 : "Request cannot have any downvotes"
assert json.target_branch == "master": "Target branch is not set to master"

def map = ["sourceBranchName ": json.source_branch, "targetBranchName ": json.target_branch]
return map

I end up with FileNotFoundException and later on, I figured out I get 404 response when trying to access this URL from that job, it works in my browser though. I assume it might be authorization issue for Jenkins machine.

I know that we've got some gitlab-plugin in Jenkins and the communication is possible (in the past we managed to trigger builds using webhooks or post build statuses back on GitLab). Can I use any other way to get this JSON in groovy script (executed at the beginning or a job)?

It turned out that it was an authentication issue.
I solved this by providing GitLab API private token in header of a request:

...
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.dabsquared.gitlabjenkins.connection.GitLabApiTokenImpl

def branch = Branch
branch = branch.replaceAll("\\s","")

// Get GitLab API token(s) already stored in Jenkins credentials
def gitlabToken = CredentialsProvider.lookupCredentials(GitLabApiTokenImpl.class).apiToken[0]
def mergeRequestURL = new URL("https://example.com/api/v4/projects/1/merge_requests/" + branch)

// Put the token in request properties before sending it
def contentJson = new JsonSlurper().parse(
    mergeRequestURL.newReader(
        requestProperties: ['Private-Token': gitlabToken.toString()]))

def map = ["Branch": contentJson.source_branch]
return map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM