Looking to run Jenkins stages in parallel dynamically. Each stage in the parallel stages is run on different agents (jenkins-agent-01, jenkins-agent-02,jenkins-agent-03).
How to trigger stages dynamically with different agents?
Below is the Jenkinsfile which contains both stages which need to be run dynamically and also sequentially.
Most of the code inside the jenkins stages is same except for agent name and function name and I would like to employ DRY.
@Library(‘jenkins-shared-lib’)_
pipeline {
agent none
stages {
stage(‘initialize’) {
agent {
label 'jenkins-agent-01'
}
steps {
script {
//code for loading env and scripts
}
}
}
stage('UnitTests') {
parallel {
stage('UnitTest-Stage1') {
agent {
label 'jenkins-agent-02'
}
steps {
script {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
try {
unitTest.function1()
}
catch (Exception e) {
caughtException = e
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
}
stage('UnitTest-Stage2') {
agent {
label 'jenkins-agent-03'
}
steps {
script {
try {
unitTest.function3()
}
catch (Exception e) {
caughtException = e
currentBuild.result = 'FAILURE'
}
}
}
}
stage('UnitTest-Stage3') {
agent {
label 'jenkins-agent-04'
}
steps {
script {
try {
unitTest.function4()
}
catch (Exception e) {
caughtException = e
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
stage(‘Analysis’) {
parallel {
stage('Analysis-Stage1') {
steps {
script {
try {
sq.function1()
}
catch (Exception e) {
caughtException = e
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
}
}