Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

Is it possible to create parallel Jenkins Declarative Pipeline stages in a loop?

I have a list of long running Gradle tasks on different sub projects in my project. I would like to run these in parallel using Jenkins declarative pipeline.

I was hoping something like this might work:

projects = [":a", ":b", ":c"]

pipeline {
    stage("Deploy"){
        parallel {
             for(project in projects){
               stage(project ) {
                   when {
                       expression {
                            someConditionalFunction(project)
                       }
                   }
                   steps {
                       sh "./gradlew ${project}:someLongrunningGradleTask"
                  }
                }   
             }
        }
    }
}

Needless to say that gives a compile error since it was expecting stage instead of for. Any ideas on how to overcome this? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was trying to reduce duplicated code in my existing Jenkinsfile using declarative pipeline syntax. Finally I was able to wrap my head around the difference between scripted and declarative syntax.

It is possible to use scripted pipeline syntax in a declarative pipeline by wrapping it with a script {} block.

Check out my example below: you will see that all three parallel stages finish at the same time after waking up from the sleep command.

def jobs = ["JobA", "JobB", "JobC"]

def parallelStagesMap = jobs.collectEntries {
    ["${it}" : generateStage(it)]
}

def generateStage(job) {
    return {
        stage("stage: ${job}") {
                echo "This is ${job}."
                sh script: "sleep 15"
        }
    }
}

pipeline {
    agent any

    stages {
        stage('non-parallel stage') {
            steps {
                echo 'This stage will be executed first.'
            }
        }

        stage('parallel stage') {
            steps {
                script {
                    parallel parallelStagesMap
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...