How to abort Jenkins pipeline build if label is not matched

Viewed 1456

I have a Jenkinsfile multibranch pipeline script, which runs on two different Jenkins systems. Jenkinsfile relies on a specific label name. In one of the systems, the label based agent is available and in another not (intentionally). In the former it runs fine. In the Jenkins system without the matching label, the job just hangs because it cant find a matching agent.

Is there a way to specify an option to abort (or not start) a build if a label is not found?

3 Answers

Some discussion here: https://issues.jenkins-ci.org/browse/JENKINS-35905

Might not be possible anytime soon

If they are calling in to a shared library then you can check for label being online/available and then fail the build

def computers = Jenkins.instance.computers
for(computer in computers){
       if(computer.isOnline()){
            labelStr = computer.node.getLabelString()
       }
       if labelStr ~= /user input/
           break;
}
System.exit(1); // no label

For a declarative pipeline it may be possible to use when{beforeAgent} to test whether a label exists.

This would only be useful where the agent is specified for a stage rather than the whole pipeline.

...and caveat that this is an as yet untested hypothesis.

Just a workaround, but in order to avoid dependency on shared lib I run the below every X minutes to clean-up culprits from queue:

import hudson.model.*

def q = Jenkins.instance.queue

q.items.each { 
  if (it =~ /someregex or match all/) {
    why = it.getWhy() 
    if (why =~ /.*There are no nodes with the label.*/) {
        println "No node found for $it.task.runId. It's stuck in damn jenkins queue forever and ever. Killing it"
        q.cancel(it.task)
    }
  }
}
Related