Jenkins parameterized job that only queues one build

后端 未结 7 836
暖寄归人
暖寄归人 2020-12-30 03:25

Imagine a Jenkins job A which takes 1 minute to run, and job B which takes 5 minutes.

If we configure job A to trigger job B, while job B is running job A may run 5

7条回答
  •  北海茫月
    2020-12-30 04:07

    Here's a more flexible option if you are only care about a few parameters matching. This is especially helpful when a job is triggered externally (i.e. from GitHub or Stash) and some parameters don't need a separate build.

    If the checked parameters match in both value and existence in both the current build and a queued build, the current build will be aborted and the description will show that a future build contains the same checked parameters (along with what they were).

    It could be modified to cancel all other queued jobs except the last one if you don't want to have build history showing the aborted jobs.

        checkedParams = [ 
        "PARAM1",
        "PARAM2",
        "PARAM3",
        "PARAM4",
    ]
    
    def buildParams = null
    def name = build.project.name
    def queuedItems = jenkins.model.Jenkins.getInstance().getQueue().getItems()
    
    yieldToQueuedItem = false
    for(hudson.model.Queue.Item item : queuedItems.findAll { it.task.getName() == name }) {
        if(buildParams == null) {    
            buildParams = [:]
            paramAction = build.getAction(hudson.model.ParametersAction.class)
            if(paramAction) {
                buildParams = paramAction.getParameters().collectEntries {
                    [(it.getName()) : it.getValue()]
                }
            }
        }
        itemParams = [:]
        paramAction = item.getAction(hudson.model.ParametersAction.class)
        if(paramAction) {
            itemParams = paramAction.getParameters().collectEntries {
                [(it.getName()) : it.getValue()]
            }
        }
    
        equalParams = true
        for(String compareParam : checkedParams) {
            itemHasKey = itemParams.containsKey(compareParam)
            buildHasKey = buildParams.containsKey(compareParam)
            if(itemHasKey != buildHasKey || (itemHasKey && itemParams[compareParam] != buildParams[compareParam])) {
                equalParams = false
                break;
            }
        }
        if(equalParams) {
            yieldToQueuedItem = true
            break
        }
    }
    
    if (yieldToQueuedItem) {
        out.println "Newer " + name + " job(s) in queue with matching checked parameters, aborting"
        build.description = "Yielded to future build with:"
        checkedParams.each {
            build.description += "
    " + it + " = " + build.buildVariables[it] } build.doStop() return } else { out.println "No newer " + name + " job(s) in queue with matching checked parameters, proceeding" }

提交回复
热议问题