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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With