在Jenkins中使用Groovy脚本取消暂停和等待的构建

uubf1zoe  于 2022-11-01  发布在  Jenkins
关注(0)|答案(1)|浏览(236)

是否有办法终止正在等待/暂停的作业,而不是终止所有正在运行的作业,并显示已停止作业的相应名称

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()
        }
      }
    }
  }

我试图重构从Cancel queued builds and aborting executing builds using Groovy for Jenkins中提取的代码,但它无法杀死那些等待/暂停的作业。

ejk8hzay

ejk8hzay1#

您可以使用以下脚本。第一部分将清除生成队列,后一部分将终止任何暂停的生成。

// 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()
           }
        } 
   }  
}

相关问题