job-dsl - How to pass credentials while creating jobs from gitlab repo branches?

2k Views Asked by At

I am creating a jobs for each application branches from github. I am not sure how to pass the credentials to the repo link?

import groovy.json.*

def project = 'app-ras'
def branchApi = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches")
def branches = new JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
def jobName = "${project}-${branchName}".replaceAll('/','-')
job(jobName) {
    scm {
        git("https://gitlab.etctcssd.com/sdadev/${project}.git", branchName)
    }
  }
}

Our project is secure project in gitlab, so how can I pass the credentials in this case?

I am sure it would redirect to login page. But I am not sure how to handle this. Any help would be greatly appreciated.

1

There are 1 best solutions below

2
On BEST ANSWER

I hope it will work in the following way:

import groovy.json.JsonSlurper

def project = 'app-ras'
def branchApi = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches")
def branches = new JsonSlurper().parse(branchApi.newReader())

branches.each {
    def branchName = it.name
    String jobName = "${project}-${branchName}".replaceAll('/', '-')
    job(jobName) {
        scm {
            git {
                branch(branchName)
                remote {
                    url("https://gitlab.etctcssd.com/sdadev/${project}.git")
                    credentials("HERE")
                }
            }
        }
    }
}

Try to substitute HERE with plain credentials (a kind of an access token) or with credential ID (of type Secret text) defined under Jenkins -> Credentials.

Also, are you using gitlab or github?

EDIT

So as far as I understood you have problems with fetching the branches names not with the Jenkins DSL. Here you can see how to fetch branches from gitlab. In groovy in can be done in the following way:

URLConnection connBranches = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches").openConnection()
connBranches.setRequestProperty("PRIVATE-TOKEN", "PASTE TOKEN VALUE HERE")
new JsonSlurper().parse(new BufferedReader(new InputStreamReader(connBranches.getInputStream())))