Search code examples
jenkinsjenkins-pipelinepipelinejenkins-groovy

Invoking a function from a shared library does not work


I wrote a groovy code that disables a job if it falls more than 3 times. When i add the code directly to the Jenkinsfile before the main pipeline, it works as expected. I decided to move the code to shared libs, added lib to jenkinsfile, call it, but nothing happens. Can you tell me what I can to do?

It works as expected:

passedBuilds = []
def call(build) {
    if(build != null && build.result != 'SUCCESS') {
        call(build.getPreviousBuild());
        passedBuilds.add(build);
    }
 }
 call(currentBuild.getPreviousBuild());
if (passedBuilds.size() > 3) {
  println "Oh no!"
  manager.build.project.disabled = true
} else {
  println "Ok!"
}

pipeline {}

It does not work

@Library('shared-libraries@main')_

disableJobInUnstableCases()

pipeline {}

Solution

  • So the working code there is:

    def iterate(build) {
      passedBuilds = []
      if (build != null && build.result != 'SUCCESS') {
        iterate(build.getPreviousBuild())
        passedBuilds.add(build)
      }
    }
    
    def checkForOverLimit() {
      if (passedBuilds.size() > 5) {
        println 'Oh no!'
        manager.build.project.disabled = true
      } else {
        println 'Ok!'
      }
    }
    
    def call() {
      iterate(currentBuild.getPreviousBuild())
      checkForOverLimit()
    }
    

    Then just call the library from pipeline