0

Is there a way to kill the waiting/paused job instead of all running jobs and displaying the corresponding name of the job which was stopped

  import java.util.ArrayList
  import hudson.model.*;
  import jenkins.model.Jenkins

  // Remove everything which is currently queued
  def q = Jenkins.instance.queue
  for (queued in Jenkins.instance.queue.items) {
    q.cancel(queued.task)
  }

  // stop all the currently running jobs
  for (job in Jenkins.instance.items) {
    stopJobs(job)
  }

  def stopJobs(job) {
    if (job in com.cloudbees.hudson.plugins.folder.Folder) {
      for (child in job.items) {
        stopJobs(child)
      }    
    } else if (job in org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) {
      for (child in job.items) {
        stopJobs(child)
      }
    } else if (job in org.jenkinsci.plugins.workflow.job.WorkflowJob) {

      if (job.isBuilding()) {
        for (build in job.builds) {
        build.doKill()
        }
      }
    }
  }

I tried to refactor the code taken from Cancel queued builds and aborting executing builds using Groovy for Jenkins but it could not able to kill those waiting/paused jobs.

Kavitha
  • 1
  • 1
  • Are you missing part of your script? I see only few recursive calls to `stopJobs`. Where are you stopping the Job? – ycr Jul 18 '22 at 19:27
  • @ycr have added the full script in the post, but it's killing the actively running jobs as well, but I need only the waiting/paused jobs to be killed and display the name of the corresponding job – Kavitha Jul 19 '22 at 03:06

1 Answers1

0

You can use the following script. The first part will clear the build queue and the latter part will kill any paused Build.

// Clear all the Pending Jobs
Jenkins.instance.queue.clear() 


// Killing all Paused Jobs
Jenkins.instance.getAllItems(Job.class).each { job ->
      job.getBuilds().each { b ->        
        if(b.isInProgress()) {
           if(b.getExecution().isPaused()){
                println "Build: " + b.getNumber() + " of Job: " +  job.getName() + " is Paused. Hence Killing!!!"
                b.doKill()
           }
        } 
   }  
}
ycr
  • 12,828
  • 2
  • 25
  • 45