在 Jenkins 管道中包装几个阶段

Wrap several stages in Jenkins pipeline

在我的声明性管道中,我有几个不需要 Xvfb 的阶段和几个需要 Xvfb 的测试阶段。

是否可以为多个阶段定义一个Jenkins wrapper?像这样:

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

无论我在几个阶段放置 wrap 块,我都会遇到编译错误:

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

由于 wrap 是一个步骤,我们必须从 stepsscript 上下文中调用它。只有后者允许我们在 wrap 块内创建嵌套阶段。试试这个:

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

        //...
    }
}

额外阶段"Test Start"可能看起来有点难看,但它确实有效。

注意:嵌套测试阶段不需要steps块,因为我们已经在script块内,所以相同的规则就像在脚本管道中一样应用。