首页 > 解决方案 > Jenkins中并行管道中的顺序阶段

问题描述

我在 Jenkins 中有一个动态脚本管道,它有许多并行阶段,但在每个阶段中,都有多个串行步骤。我浪费了几天时间试图让它工作:无论我尝试什么,所有串行子阶段都集中在一个阶段!这是我现在拥有的:

node () {
    stage("Parallel Demo") {
        // Canonical example to run steps in parallel

        // The map we'll store the steps in
        def stepsToRun = [:]

        for (int i = 1; i < 5; i++) {
            stepsToRun["Step${i}"] = { node {
                echo "start"
                sleep 1
                echo "done"
            }}
        }
        // Actually run the steps in parallel
        // parallel takes a map as an argument
        parallel stepsToRun
    }
}

它给了我这个漂亮的并行管道:

在此处输入图像描述

但是,当我添加一个串行阶段时,又名:

node () {
    stage("Parallel Demo") {
        // Run steps in parallel

        // The map we'll store the steps in
        def stepsToRun = [:]

        for (int i = 1; i < 5; i++) {
            stepsToRun["Step${i}"] = { node {
                stage("1") {
                    echo "start 1"
                    sleep 1
                    echo "done 1"
                }
                stage("2") {
                    echo "start 2"
                    sleep 1
                    echo "done 2"
                }                
            }}
        }
        // Actually run the steps in parallel
        // parallel takes a map as an argument
        parallel stepsToRun
    }
}

我得到了这个丑陋的东西,它看起来完全一样:

在此处输入图像描述

为了增加进攻,我看到了执行的子步骤。如何让我的子步骤显示为阶段?

此外,如果有一种方法可以使声明性管道具有动态阶段(顺序和并行),我完全赞成。我发现您可以执行静态顺序阶段,但几乎不知道如何在不回到脚本化管道的情况下使其动态化。

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


这是您如何做您想做的事情的方法

def stepsToRun = [:]

pipeline {
    agent none

    stages {
        stage ("Prepare Stages"){
            steps {
                script {
                    for (int i = 1; i < 5; i++) {
                        stepsToRun["Step${i}"] = prepareStage("Step${i}")
                    }   
                    parallel stepsToRun
                }
            }
        }
    }
}

def prepareStage(def name) {
    return {
        stage (name) {
            stage("1") {
                echo "start 1"
                sleep 1
                echo "done 1"
            }
            stage("2") {
                echo "start 2"
                sleep 1
                echo "done 2"
            }
        }
    }
}

在此处输入图像描述


推荐阅读