Groovy script to pull the jobs starting with a given name

991 Views Asked by At

I would like to get the list of jobs starting with a given name, followed by updating the label node on which the job can run. I did the following and was not successful. Any inputs in what I am missing here.

import hudson.model.*;
import hudson.util.*;
import hudson.model.labels.*;
import jenkins.model.*;
import hudson.FilePath.FileCallable;
import hudson.slaves.OfflineCause;
import hudson.node_monitors.*;


buildableItems = Jenkins.instance.getAllItems.each {job ->
    job.name.startsWith("Automation -")
    println job.fullName;
}

for(item in buildableItems) {
    job.assignedlabel = new LabelAtom('new-label-name')
    item.save()
}
2

There are 2 best solutions below

0
On

The each statement that you are suing is just going over the elements and running the closure on them but it doesn't return anything. Instead you should filter your list with findAll, then for returned filtered list run the code the changes the labels:

import jenkins.*
import hudson.model.labels.*;

filtredJobs =  Jenkins.instance.items.findAll { job ->
    job.name.startsWith("Automation -")
}

// Update the label for the filtered jobs
filtredJobs.each { job ->
    job.assignedlabel = new LabelAtom('new-label-name')
    item.save()
}

Or alternatively use each and run both the condition and the configuration in the same iteration:

import jenkins.*
import hudson.model.labels.*;

Jenkins.instance.items.each { job ->
    if (job.name.startsWith("Automation -")) {
        job.assignedlabel = new LabelAtom('new-label-name')
        item.save()
    }
}
0
On

Thankyou @NoamHelmer I was getting a format error on the output job name values. Due to which the label was modified and threw error on the job name format but could not proceed to the next job name. I was able to fix it by a continue statement.

import hudson.model.labels.*
import jenkins.model.Jenkins  

def views = ["Automation – DEV", "Automation – PROD", "Automation – QA", "Automation – Staging"]
 
for (view in views) {

  def buildableItems = Jenkins.instance.getView(view).items.each {
  println it.fullName

  }
  for (item in buildableItems) {
    try {
      item.assignedLabel = new LabelAtom('New_Label_name') 
    } catch (Exception e) {
      continue;
    }
    println(item.name + " > " + item.assignedLabel)
}

}

Thankyou for your input again!!