Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I build stages with a function in a Jenkinsfile?

I'd like to use a function to build some of the stages of my Jenkinsfile. This is going to be a build with a number of repetitive stages/steps - I'd not like to generate everything manually.

I was wondering if it's possible to do something like this:

_make_stage() {
    stage("xx") {
        step("A") {
            echo "A"
        }

        step("B") {
            echo "B"
        }
    }
}

_make_stages() {
    stages {
        _make_stage()
    }
}

// pipeline starts here!
pipeline {
    agent any
    _make_stages()
}

Unfortunately Jenkins doesn't like this - when I run I get the error:

WorkflowScript: 24: Undefined section "_make_stages" @ line 24, column 5.
       _make_stages()
       ^

WorkflowScript: 22: Missing required section "stages" @ line 22, column 1.
   pipeline {
   ^

So what's going wrong here? The function _make_stages() really looks like it returns whatever the stages object returns. Why does it matter whether I put that in a function call or just inline it into the pipeline definition?

like image 422
Salim Fadhley Avatar asked May 09 '17 23:05

Salim Fadhley


1 Answers

As explained here, Pipeline "scripts" are not simple Groovy scripts, they are heavily transformed before running, some parts on master, some parts on slaves, with their state (variable values) serialized and passed to the next step. As such, every Groovy feature is not supported, and what you see as simple functions really is not.

It does not mean what you want to achieve is impossible. You can create stages programmatically, but apparently not with the declarative syntax. See also this question for good suggestions.

like image 157
Hugues M. Avatar answered Oct 23 '22 01:10

Hugues M.