groovy to list Jenkins jobs with GIT URL used in j

2019-08-30 02:05发布

问题:

We need to print Jenkins jobs URLs and GIT URL configured inside these jobs.

For example:

Assume my Jenkins URL is : http://localhost:8080 & my git URL is ssh://git:424

If i run groovy code from Jenkins, It should return:

http://localhost:8080/job_name1 | ssh://git:424/repo_name1 (GIT URL configured in SCM section of job_name1)

http://localhost:8080/job_name2 | ssh://git:424/repo_name2 (GIT URL configured in SCM section of job_name2)

I have below code to list jobs :

Jenkins.instance.getAllItems(AbstractProject.class).each {it ->
println it.fullName;
}

and below code to list SCM value:

Jenkins.instance.getAllItems(hudson.model.AbstractProject.class).each {it ->
  scm = it.getScm()
  if(scm instanceof hudson.plugins.git.GitSCM)
  {
    println scm.getUserRemoteConfigs()[0].getUrl()
  }
}
println "Done"

Above code first returns Jenkins job URLS and then SCM URl but i have to map it manually what SCM belongs to what Jenkins job URL.

Is there a way, i can print Jenkins job URL and its SCM value using groovy.

Appreciate help !

回答1:

If you are using a WorkflowJob then the below snippet should work for you.

Jenkins.instance.getAllItems(Job.class).each{
scm = it.getTypicalSCM();
project = it.getAbsoluteUrl();
if (scm instanceof hudson.plugins.git.GitSCM) {
scm.getRepositories().each{
    it.getURIs().each{
        println(project.toString() +":"+ it.toString());
    }
  }
 }
}