如何在外部函数中定义Jenkinsfile的并行阶段?

时间:2018-12-30 11:21:43

标签: jenkins jenkins-pipeline jenkins-declarative-pipeline

此最小管道有效:

pipeline {
    agent any
    stages {
        stage('test') {
            parallel {
                stage('test-1') {
                    steps {
                        sh "echo test1"
                    }
                }
                stage('test-2') {
                    steps {
                        sh "echo test2"
                    }
                }
            }
        }
    }
}

我们在parallel块中有几个测试阶段,因此我们遇到了Method Code too large错误,Jenkins伙计显然不打算修复。

我想在外部函数中定义并行阶段,如下所示:

pipeline {
    agent any
    stages {
        stage('test') {
            parallel test_func()
        }
    }
}

def test_func() {
    return {
            stage('test-1') {
                steps {
                    sh "echo test1"
                }
            }
            stage('test-2') {
                steps {
                    sh "echo test2"
                }
            }
        }
}

但是,这不适用于我们尝试过的多种语法。

谢谢!

3 个答案:

答案 0 :(得分:0)

如示例here所示,它期望将任意标识符的映射作为键,并将包含代码的闭包作为值。所以(未试用)类似:

def test_func() {
    return [
        test1: {
            stage('test-1') {
                steps {
                    sh "echo test1"
                }
            }
        },
        test2: {
            stage('test-2') {
                steps {
                    sh "echo test2"
                }
            }
        }
    ]
}

答案 1 :(得分:0)

检查我对this question的回答。

您需要将并行阶段放在变量而不是函数中。因此,可能是这样的:

def test_func = [
    "test1": {
        echo "test1"
    },
    "test2": {
        echo "test2"
    }
]

pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                script {
                    parallel test_func
                }
            }
        }
    }
}

答案 2 :(得分:0)

您可以这样做:

def createStages() {
  stage_map = [:]
  stage_map.put('test-1', {echo 'test1'})
  stage_map.put('test-2', {echo 'test2'})
  return stage_map
}

pipeline {
  agent any
  stages {
    stage('test') {
      steps{
        script { parallel(createStages()) }
      }
    }
  }
}