3

Jenkins: List All Jobs – Groovy Script

 2 years ago
source link: https://www.shellhacks.com/jenkins-list-all-jobs-groovy-script/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Jenkins: List All Jobs – Groovy Script

The easiest way to get a list of all Jenkins jobs is by executing an appropriate Groovy script using a Jenkins script console feature.

This note shows two examples of Groovy scripts for listing the Jenkins jobs.

The first script simply prints the list of all Jenkins jobs while the second one additionally lets you to identify how the last build of each job was triggered, e.g. manually by user, triggered by commit, by schedule etc.

Cool Tip: Disable automatic Jenkins job triggering during SCM scanning for the new branches! Read more →

List All Jobs in Jenkins

To get a list of all Jenkins jobs including the jobs inside folders (recursively) and the folders themselves, go to ⚙️ Manage Jenkins → 📝 Script Console and execute:

Jenkins.instance.getAllItems(AbstractItem.class).each {
    println it.fullName + " - " + it.class
};

You can also get the list of all Jenkins jobs using the following Groovy script:

Jenkins.instance.getAllItems(Job).each{
  def jobBuilds=it.getBuilds()G
  // Check the last build only
  jobBuilds[0].each { build ->
    def runningSince = groovy.time.TimeCategory.minus( new Date(), build.getTime() )
    def currentStatus = build.buildStatusSummary.message
    def cause = build.getCauses()[0]
    def causeClass = cause.getClass().getSimpleName()
    switch (causeClass) {
      case "BranchEventCause":
        println "[Branch Event] ${build}"
        break;
      case "BranchIndexingCause":
        println "[Branch Indexing] ${build}"
        break;
      case "UserIdCause":
        def user = cause.getUserId()
        println "[${user}] ${build}"
        break;
      case "TimerTriggerCause":
        println "[Timer Trigger] ${build}"
        break;
    }
  }
}
return

This script not only lists all the Jenkins jobs but also lets you to determine how the last build of each job was triggered.

Sample output of the Jenkins jobs listing using the Groovy script above:

[user34283] Prod/deploy #32
[user23423] Dev/build #87
[Time Trigger] Housekeeping/docker-cleanup #432
[Branch Indexing] Testing/build-docker-image/master #1
[Branch Indexing] Testing/build-docker-image/dev #1
[Branch Event] Testing/notify/master #23

Cool Tip: Schedule Jenkins build periodically! Read more →


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK