Parthivi Varshney
Parthivi Varshney

Reputation: 1

Unable to return a declaratively defined stage from closure to jenkins shared library

I have been working on creating a jenkins shared library, and it works perfectly for a generalized pipeline template. Recently I had the need to pass an extra user-defined stage to my generalized pipeline. I am using closure to do so, but facing some issues with it. I would like for the closure to return a declarative stage which has its own agent, steps and other components as shown in the code samples below (refer the following images) :

Closure defined in .jenkinsfile : Closure defined in .jenkinsfile

Call to closure from jenkins shared library Call to closure from jenkins shared library

Error Message : Error Message

Please let me know how can I achieve the above functionality.

Upvotes: 0

Views: 151

Answers (1)

Rafa Alonso
Rafa Alonso

Reputation: 887

Use a scripted pipeline to run the declarative pipeline script.

Create a map with the type, actions, contents, etc of the stages. Then read and execute the contents of the map within the pipeline.

Copy-paste this pipeline script in a pipeline job (uncheck the Groovy Sandbox, if required):

import groovy.transform.TupleConstructor

@TupleConstructor
class Task implements Serializable {
   private static final long serialVersionUID = 1L
   String description
   Closure action
}

// fill the map with contents from any source, e.g. from your declarative pipeline in .jenkinsfile
tasks = [
    new Task(
        description: 'say hello world',
        action: {
            sh "echo hello world"
        }
    )
]

// execute the actions
node('built-in') {
    tasks.each { task ->
        stage("${task.description}") {
            task.action()
        }
    }     
}

Upvotes: 0

Related Questions