Bohdan Nesteruk
Bohdan Nesteruk

Reputation: 914

Wrap several stages in Jenkins pipeline

In my declarative pipeline I have several stages where Xvfb is not required and several testing stages, where it is.

Is it possible to define a Jenkins wrapper ones for several stages? Something like this:

  pipeline {
        agent any

        stages {
            stage('Build the context') {
                steps {
                    echo 'No Xvfb here'
                }
            }
            wrap([$class: 'Xvfb', screen: '1920x1080x24']) {
                stage('Test Suite 1') {
                    steps {
                        echo 'Use Xvfb here'
                    }
                }

                stage('Test Suite 2') {
                    steps {
                        echo 'Use Xvfb here'
                    }
                }
            }

            stage('cleanup') {
                steps {
                    echo 'No Xvfb here'
                }
            }
        }

I'm getting compilation errors wherever I put the wrap block for several stages:

WorkflowScript: 10: Expected a stage @ line 10, column 17.
               wrap([$class: 'Xvfb', screen: '1920x1080x24']) 

Upvotes: 2

Views: 6174

Answers (1)

zett42
zett42

Reputation: 27756

As wrap is a step, we have to call it from a steps or script context. Only the latter allows us to create nested stages inside of a wrap block. Try this:

pipeline {
    agent any

    stages {
        stage('Build the context') {
            steps {
                echo 'No Xvfb here'
            }
        }
        stage('Test Start') {
            steps {
                script {
                    wrap([$class: 'Xvfb', screen: '1920x1080x24']) {
                        stage('Test Suite 1') {
                            echo 'Use Xvfb here'
                        }

                        stage('Test Suite 2') {
                            echo 'Use Xvfb here'
                        }
                    }
                }
            }
        }

        //...
    }
}

The extra stage "Test Start" may look a bit ugly, but it works.

Note: There are no steps blocks required in the nested test stages, because we are already inside a script block, so the same rules as in scripted pipeline apply.

Upvotes: 3

Related Questions