0

I have a github multibranch pipeline, in declarative format. It is configured to trigger on pushes to pull request branches (ie, branches which are included in pull requests to a target branch, say main.

If a new commit comes in before the execution of a previous commit is finished, this will trigger a concurrent build of the pipeline. I want to maintain this behaviour, but need to know if there is a new pipeline running in one of the stages.

Ie I want a groovy script step like this pseudo code:

if (build_number + 1) is_currently_running
  do one thing
else
  do something else

Is there any way to ask Jenkins if build n+1 is running?

1 Answer 1

1

This should be fairly straightforward to do in a script block. I don't think there's a declarative-native way to do this.

I use this script block to cancel builds for earlier (i.e. outdated) revisions of PRs:

script {
  // currentBuild is a Pipeline-builtin variable for accessing the Build object
  // https://www.jenkins.io/doc/book/pipeline/getting-started/#global-variable-reference
  def build = currentBuild

  while(true) {
    build = build.getPreviousBuild()

    // exit the loop if we have finished iterating over builds
    // (groovy doesn't have a do...while feature)
    if (build == null) break

    def rawBuild = build.rawBuild

    if (rawBuild.isBuilding()) {
      // abort the build
      rawBuild.doTerm()
    }
  }
}

As you can hopefully see, this iterates over all previous builds and uses the isBuilding() method to find ones that are currently running.

If you want to check later builds instead of previous ones, you can use getNextBuild() instead (I believe the API doc is here, it's been a while since I wrote this so this might be the wrong class).

And if you want to check only one directly adjacent build instead of all earlier/later builds, you can just omit the loop and only call getPreviousBuild()/getNextBuild() once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.