Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define and use function inside Jenkins Pipeline config?

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?

like image 898
Dr.eel Avatar asked Feb 10 '17 11:02

Dr.eel


People also ask

How do you use parameters in Jenkins pipeline?

Jenkins Pipeline Parameters:All of them should be defined in the parameters section of the pipeline. After running the pipeline for the first time, Build with Parameters is shown in the pipeline menu. From now on, when you want to build, you should set parameters before that being start.

How do you pass a parameter in Jenkins pipeline script?

Any Jenkins job or pipeline can be parameterized. All we need to do is check the box on the General settings tab, “This project is parameterized”: Then we click the Add Parameter button.

How do we configure Jenkins pipeline?

Click the New Item menu within Jenkins. Provide a name for your new item (e.g. My-Pipeline) and select Multibranch Pipeline. Click the Add Source button, choose the type of repository you want to use and fill in the details. Click the Save button and watch your first Pipeline run.


1 Answers

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) } 
like image 106
Jon S Avatar answered Sep 27 '22 21:09

Jon S