Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

Jenkins execute all sub jobs before marking a top job fail or pass?


def jobs = [
    'subjob1': true,
    'subjob2': false,
    'subjob3': true
]

pipeline
{
    agent { label "ag1" }

    stages
    {
        stage('stage1')
        {
            steps
            {
                script
                {
                    jobs.each
                    {
                        if ("$it.value".toBoolean())
                        {
                            stage("Stage $it.key")
                            {
                                build([job:"$it.key", wait:true, propagate:true])
                            }
                        }
                    }
                }
            }
        }
    }
}

This Jenkins job triggers other sub-jobs (via pipeline build step): subjob1, subjob2, subjob3. If any of the sub-jobs fail, this job immediately fails (propagate:true).

However, what I'd like to do is continue executing all jobs. And mark this one as failed if one or more sub-jobs fail. How would I do that?


Solution

  • Here is how you can do it. You can simply use a catchError block for this.

    def jobs = [
        'subjob1': true,
        'subjob2': false,
        'subjob3': true
    ]
    
    pipeline
    {
        agent any
    
        stages
        {
            stage('stage1')
            {
                steps
                {
                    script
                    {
                        jobs.each
                        {
                            if ("$it.value".toBoolean())
                            {
                                stage("Stage $it.key")
                                {
                                   catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') 
                                    {
                                        echo "Building"
                                        build([job:"$it.key", wait:true, propagate:true])
                                    } 
                                }
                            }
                        }
                    }
                }
            }
        }
    }