Reputation: 137
stages {
stage('Setup') {
}
stage('Parallel Stage') {
parallel {
stage('Executor 1') {
}
stage('Executor 2') {
}
stage('Executor 3') {
}
stage('Executor 4') {
}
}
}
}
Above is a skeleton of my Jenkins pipeline that has a setup stage and then a parallel stage that does the same thing four times for faster execution time.
Is there a way to define a stage as a variable to reduce the 4x code repetition and to reduce the number of edits I would have to make?
Upvotes: 1
Views: 935
Reputation: 1160
Yes, best way is to defined a function which generates stage and can be called in parallel.
Presuming that you are executing the stages into 1 agent in parallel.
In below sample pipeline generateStage
is a function which replaces nested stages with function.
def jobs = ["Executor1", "Executor2", "Executor3"]
def parallelStagesMap = jobs.collectEntries {
["${it}" : generateStage(it)]
}
def generateStage(job) {
return {
stage("${job}") {
echo "Running stage ${job}."
}
}
}
pipeline {
agent any
stages {
stage('setup') {
steps {
echo 'This stage will be executed first.'
}
}
stage('parallel stage') {
steps {
script {
parallel parallelStagesMap
}
}
}
}
}
Output of the pipeline is as below:
For more details please see my answer LINK
Only drawback is that you can not execute this pipeline arrangement directly after stages
thats why parallelStageMap
is called inside the script.
Upvotes: 4