Jenkins管道(并行&&动态)?

lon*_*ony 4 jenkins jenkins-pipeline

我有简单的并行管道(见代码),我和Jenkins 2.89.2一起使用.另外,我使用参数,现在希望能够通过在作业执行之前提供参数来自动减少deployVM A..Z阶段的数量.

如何通过提供参数动态构建我的管道?

到目前为止研究:

我想要的伪代码 - 动态生成:

pipeline {

    agent any

    parameters {
        string(name: 'countTotal', defaultValue: '3')
    }

    stages {

       stage('deployVM') {

        def list = [:]
        for(int i = 0; i < countTotal.toInteger; i++) {
            list += stage("deployVM ${i}") {
                steps {
                    script {
                        sh "echo p1; sleep 12s; echo phase${i}"
                    }

                }
            }
        }

        failFast true
        parallel list
       }

   }

}
Run Code Online (Sandbox Code Playgroud)

我到目前为止的代码 - 执行并行但是静态的:

pipeline {

    agent any
    stages {

       stage('deployVM') {
        failFast true
        parallel {
            stage('deployVM A') {
                steps {
                    script {
                        sh "echo p1; sleep 12s; echo phase1"
                    }

                }
            }
            stage('deployVM B') {
                steps {
                    script {
                        sh "echo p1; sleep 20s; echo phase2"
                    }

                }
            }
        }
       }

   }

}
Run Code Online (Sandbox Code Playgroud)

Vit*_*nko 8

虽然问题假设使用声明性管道,但我建议使用脚本化管道,因为它更灵活.
您的任务可以通过这种方式完成

properties([
    parameters([
        string(name: 'countTotal', defaultValue: '3')
    ])
])

def stages = [failFast: true]
for (int i = 0; i < params.countTotal.toInteger(); i++) {
    def vmNumber = i //alias the loop variable to refer it in the closure
    stages["deployVM ${vmNumber}"] = {
        stage("deployVM ${vmNumber}") {
            sh "echo p1; sleep 12s; echo phase${vmNumber}"
        }
    }
}

node() {
    parallel stages
}
Run Code Online (Sandbox Code Playgroud)

另外,请看一下片段生成器,它允许您生成一些脚本化的管道代码.