Cancel queued builds and aborting executing builds using Groovy for Jenkins

前端 未结 9 2125
礼貌的吻别
礼貌的吻别 2020-12-01 00:28

For Jenkins using a Groovy System Script, is there a way to easily search the build queue and list of executing builds for some criteria (specifically a parameter that match

9条回答
  •  醉梦人生
    2020-12-01 01:14

    After some investigation, I came up with this code which works absolutely fine for me. It clears the queue and also aborts all the jobs currently getting executed.

    Prerequisites:

    1. 'All' view contains all the jobs
    2. Use System groovy
    import jenkins.model.Jenkins
    import hudson.*
    import hudson.model.*
    import jenkins.*
    
    // Remove everything which is currently queued
    
    Jenkins.instance.queue.clear()
    def buildingJobs = Jenkins.instance.getAllItems(Job.class).findAll {
        it.isBuilding()
    }
    
    buildingJobs.each {
        def jobName = it.toString()
        def val = jobName.split("\\[|\\]")
    
        // 'Abort jobs' is the name of the job I have created, and I do not want it to abort itself.
    
        if((val[1].trim())!='Abort jobs') {
            def job = Jenkins.instance.getItemByFullName(val[1].trim())
            for (build in job.builds) {
                if (build.isBuilding()) {
                    println(build)
                    build.doStop();
                }
            }
        }
    }
    
    

提交回复
热议问题