是否可以在循环中创建并行的 Jenkins 声明式流水线阶段? [英] Is it possible to create parallel Jenkins Declarative Pipeline stages in a loop?
问题描述
我在我的项目中的不同子项目上有一个长期运行的 Gradle 任务列表.我想使用 Jenkins 声明式管道并行运行这些.
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"
}
}
}
}
}
}
不用说,这会导致编译错误,因为它期待的是 stage 而不是 for.关于如何克服这个问题的任何想法?谢谢
Needless to say that gives a compile error since it was expecting stage instead of for. Any ideas on how to overcome this? Thanks
推荐答案
我试图使用声明式管道语法减少现有 Jenkinsfile 中的重复代码.最终,我能够理解脚本化语法和声明性语法之间的区别.
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.
看看我下面的例子:从 sleep 命令唤醒后,您会看到所有三个并行阶段同时完成.
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
}
}
}
}
}
这篇关于是否可以在循环中创建并行的 Jenkins 声明式流水线阶段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!