Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use 'parallel' option in jenkins pipeline in the 'post' section?

I looked at many pipeline examples and how to write the post build section in a pipeline script. But never got my answer i was looking for. I have 4 jobs - say Job A,B,C and D. I want job A to run first, and if successful it should trigger Job B,C,D in parallel. If Job A fails, it should trigger only Job B. Something like below:

pipeline {
    agent any

stages {
    stage('Build_1') {
        steps {
            sh '''
               Build Job A
            '''
        }
    }

post {
    failure {
        sh '''
            Build Job B
        '''
    }
    success {
         sh '''
             Build Job B,C,D in parallel
         '''
    }
}
}

I tried using 'parallel' option in post section but it gave me errors. Is there a way to build Job B,C,D in parallel, in the post 'success' section?

Thanks in advance!

like image 541
cad.sneha Avatar asked Jun 28 '17 15:06

cad.sneha


1 Answers

The parallel keyword actually can work inside a post condition as long as it is encapsulated inside a script block, as the script blocks is just a fallback to the scripted pipeline which will allow you to run parallel execution step wherever you want.
The following should work fine:

pipeline {
    agent any
    stages {
        stage('Build_1') {
            steps {
                //  Build Job A
            }
        }
    }

    post {
        failure {
            // run job B
            build job: 'Job-B'
        }
        success {
            script {
                // run jobs B, C, D in parallel 
                def jobs = ['Job-B', 'Job-C', 'Job-D']
                parallel jobs.collectEntries { job ->
                    ["Building ${job}" : {
                        build job: job
                    }]
                }
            }
        }
    }
}

This is just an example and specific parameters or configuration (for the build keyword) can be added to each job execution according to your needs.

like image 96
Noam Helmer Avatar answered Sep 28 '22 19:09

Noam Helmer