How to define and use function inside Jenkins Pipeline config?

Dr.eel picture Dr.eel · Feb 10, 2017 · Viewed 97.4k times · Source

I'm trying to create a task with a function inside:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: $projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: $project, parameters: $params
    doCopyMibArtefactsHere($projectName)
}


node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

But this gives me an exception:

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

Is there any way to use embedded functions within a Pipeline script?

Answer

Jon S picture Jon S · Feb 10, 2017

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}