Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list the jenkins jobs script path programmatically

I'd like to create a groovy script to run on the jenkins console to list the job definition with the repository used and the script path (the jenkinsfile), with an output like this:

JobName -> git repository -> script path

So far I was able to list the job name and the git repository, but I can't find a way to get the script path. It doesn't seem contained in the GitSCM plugin, but I can't find a way to obtain it through the WorkflowJob. This is my current code:

Jenkins.instance.getAllItems(Job.class).each{
  jobName = it.getName()
  if(it instanceof FreeStyleProject){
   return
  }
  scm = it.getTypicalSCM();
  if (scm instanceof hudson.plugins.git.GitSCM) {
    scm.getRepositories().each{
        it.getURIs().each{
            println(jobName +"-> "+ it.toString());
        }
    }
  }
}

How can I retrieve the script path?

like image 299
Mikyjpeg Avatar asked Nov 15 '22 20:11

Mikyjpeg


1 Answers

I found a way to retrieve the path of the script. I've tested it for WorkflowJob. The following code prints the script itself if it's a local script, or the path if it's a remote one:

Jenkins.instance.getAllItems(Job) { job ->
   if(job instanceof WorkflowJob) {
       if(job.getDefinition() instanceof org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) {
           println("Local script: ")
           println(job.getDefinition().getScript())
       }
       else {
           println("Remote script path: " + job.getDefinition().getScriptPath())
       }
   }
}

For FreeStyleProject something like this can be done:

   import hudson.tasks.Shell
   ...
   if(job instanceof hudson.model.FreeStyleProject) {
      println("Script: ")
      job.builders.findAll { it in Shell }.collect { shell -> println(shell.command) }
   }

I still haven't found a way for Multibranch pipelines, but since they are composed of WorkflowJobs, some extra effort might give the wanted result.

NOTE: Instead of using the getScriptPath() function, the property scriptPath can be used as well. Sometimes job.getDefinition() returns an object of type SCMBinder, which does not have the getScriptPath() method, but the property can be used there.

like image 97
theUndying Avatar answered Dec 01 '22 00:12

theUndying