Hadfull code snippet I'm using for getting git branches from remote repos inside Jenkins pipeline. It uses already defined Jenkins credential to access the repo.
import groovy.json.JsonSlurper
import hudson.FilePath
import jenkins.model.Jenkins
import hudson.model.*
def credentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
Jenkins.instance,
null,
null
);
def owner = '<Git oowner or organization>'
def project = '<git repo name>'
def github_user
def github_pass
for (c in credentials) {
if (c.id == "<jenkins credential id>") {
github_user = c.username
github_pass = c.password
}
}
def authString = "${github_user}:${github_pass}".getBytes().encodeBase64().toString();
URLConnection connBranches = new URL("https://api.github.com/repos/${owner}/${project}/branches?page=1&per_page=50").openConnection();
connBranches.setRequestProperty("Authorization", "Basic ${authString}");
def branches = new groovy.json.JsonSlurper().parse(new BufferedReader(new InputStreamReader(connBranches.getInputStream())));
def branch_list = []
def branchesMatch = ".*"
branches.each {
def branchName = it.name
if (branchName =~ /$branchesMatch/) {
branch_list.add(branchName)
}
}
return branch_list