Jenkins-pipeline: No such DSL method

9.1k Views Asked by At

I have a Jenkins Pipeline JOB where I declared some stages that use an external function that I created by myself in the same groovy script.

errorList = ["badGatewayMsg", "closedByRemoteHostMsg", "connectionTimedOut"]
def boolean someFunction(name) {
    String jobLog = jenkins.model.Jenkins.instance.getItemByFullName(name).lastBuild.log
    for (error in errorList) {
        if (jobLog.contains(error))
            return true
    }
    return false
}

stage('stage1') {
        if(someFunction('job1Name'))
           // do Something
    }

stage('stage2') {
        if(someFunction('job2Name'))
           // do Something
    }

When I want to start this pipeline build i get the following error:

java.lang.NoSuchMethodError: No such DSL method 'someFunction' found among steps ....

Thanks for your help!

1

There are 1 best solutions below

0
On

Out of curiosity I copied the code into my local Jenkins - and it worked (after fixen obvious issues like creating the missing jobs and fixing the if conditions).

Nevertheless to get the code clean you'll need to:

  1. Get rid of the def keyword (or alternatively get rid of the data type definition boolean). You might want to check: Groovy: "def" keyword vs concrete type

  2. Add the @NonCPS keyword when accessing Jenkins internals which are not serializable.

  3. For completeness: In addition to that of course for accessing the Jenkins internals you need to switch of the sandbox mode or put your code into a global shared library.

Here's my working example:

errorList = ["badGatewayMsg", "closedByRemoteHostMsg", "connectionTimedOut"]
@NonCPS
boolean someFunction(name) {
    String jobLog = jenkins.model.Jenkins.instance.getItemByFullName(name).lastBuild.log
    for (error in errorList) {
        if (jobLog.contains(error))
            return true
    }
    return false
}

stage('stage1') {
    if(someFunction('job1Name')) {
       // do Something
    }
}

stage('stage2') {
    if(someFunction('job2Name')) {
       // do Something
    }
}