Jenkins pipeline with multiple stages after a stage


pipeline {
    agent any

    stages {
        stage('Stage 1') {
            // Add your Stage 1 steps here
        }

        stage('Stage 2') {
            // Add your Stage 2 steps here
        }

        stage('Stage 3') {
            parallel {
                stage('Stage 3.1') {
                    when {
                        expression {
                            return currentBuild.result == 'SUCCESS'
                        }
                    }
                    steps {
                        // Add your Stage 3.1 steps here
                    }
                }

                stage('Stage 3.2') {
                    when {
                        expression {
                            return currentBuild.result == 'SUCCESS'
                        }
                    }
                    steps {
                        // Add your Stage 3.2 steps here
                    }
                }
            }
        }

        stage('Stage 4') {
            parallel {
                stage('Stage 4.1') {
                    when {
                        expression {
                            return currentBuild.result == 'SUCCESS' && previousStageStatus('Stage 3.1') == 'SUCCESS'
                        }
                    }
                    steps {
                        // Add your Stage 4.1 steps here
                    }
                }

                stage('Stage 4.2') {
                    when {
                        expression {
                            return currentBuild.result == 'SUCCESS' && previousStageStatus('Stage 3.2') == 'SUCCESS'
                        }
                    }
                    steps {
                        // Add your Stage 4.2 steps here
                    }
                }
            }
        }
    }
}

def previousStageStatus(stageName) {
    def build = currentBuild.rawBuild
    def previousStage = build.getPreviousBuild()?.getExecutor()?.getCurrentExecutable()?.getParent()
    def result = previousStage?.getBuildByNumber(build.getNumber() - 1)?.getStepByName(stageName)?.getResult()
    return result?.toString()
}

Leave a Reply

Your email address will not be published. Required fields are marked *