Jasmine Jasmine - 2 months ago 13x
Groovy Question

how to end a jenkins build with a specific parameter

I trigger a build called testAUT with parameter

. I trigger the same build with the same parameter.

I want when that happens that the earlier build gets killed. How can I do that using Jenkins? I want to be able to end a build with the same parameter as the current build.


If you're OK with using the Groovy Plugin and Jenkins Rest Api, here are the steps needed to do what you want.

  1. Install the Groovy Plugin.
  2. Go to the job's configure page.
  3. Add the 'fracture_no' build parameter with default value of 125.
  4. Enable 'Execute concurrent builds if necessary' in the General section
  5. Add a 'Execute Groovy script' build step as the first step in the job
  6. Add the following code to the groovy step

def parameterName = "fracture_no";
def jenkinsUrl = System.getenv('JENKINS_URL');
def buildNumber = System.getenv('BUILD_NUMBER').toInteger();
def jobUrl = jenkinsUrl + "job/" + System.getenv('JOB_NAME');
def buildNumberUrl = jobUrl + "/" + buildNumber;
def myParameter = System.getenv(parameterName);

def projectXml = new XmlSlurper().parseText(new URL(jobUrl + "/api/xml").getText());
projectXml.build.each {
  def previousBuildNumber = it.number.text().toInteger();
  if(previousBuildNumber < buildNumber)
    def previousBuildNumberUrl = jobUrl + "/" + previousBuildNumber;
    def jobXml = new XmlSlurper().parseText(new URL(previousBuildNumberUrl + "/api/xml").getText());
    if(jobXml.building.text() == "true")
      jobXml.action.parameter.each {
        if(it.name.text() == parameterName) {
          if(it.value.text() == myParameter) {
            def url = new URL(previousBuildNumberUrl + "/stop");
            def connection = url.openConnection();
            println "Stopping " + previousBuildNumber;

  1. Add another build step that takes a long time. If you just want to test, then add the following Windows Batch Command step that sleeps for 100 seconds.
    ping -n 100 > nul
  2. Kick off the job twice using the default parameter value of 125 (or as many times as you want).
  3. Everything but the latest build should be stopped.