How to define and use function inside Jenkins Pipeline config?

JenkinsGroovyJenkins Pipeline

Jenkins Problem Overview


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?

Jenkins Solutions


Solution 1 - Jenkins

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)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDr.eelView Question on Stackoverflow
Solution 1 - JenkinsJon SView Answer on Stackoverflow