Andrea Bellizzi
Andrea Bellizzi

Reputation: 497

Jenkins pipeline trigger job and get results available in post operation

I have a pipeline with stage that trigger another job. I want to get the result of the triggered job and use it in post action. I'm doing this:

stage('Stage 1') {
                steps{
                    script {
                        echo "Trigger another job"
                            jobResult = build job:
                            'urltojob',
                                parameters: [
                                    ],
                                    wait: true,
                                    propagate: true;
                    }
                }
                post {
                    always {
                        script {

                            echo jobResult.getResult()
                            echo jobResult.getAbsoluteUrl()
                            echo jobResult.getDurationString()
                            
                        }
                    }
                }
            }

When the triggered job succeed, everything works, but when the job fails I get an error: Error when executing always post condition: groovy.lang.MissingPropertyException: No such property: jobResult for class: groovy.lang.Binding How can I solve this?

Upvotes: 1

Views: 2148

Answers (2)

Michael Kemmerzell
Michael Kemmerzell

Reputation: 5256

You can declare a global variable and set the value so you can access it everywhere. Your issue is that jobResult does not exist in the scope of your post-stage.

def result // this is our global variable

pipeline {
...
stage('Stage 1') {
            steps{
                script {
                    echo "Trigger another job"
                        result = build job:
                        'urltojob',
                            parameters: [
                                ],
                                wait: true,
                                propagate: true;
                }
            }
            post {
                always {
                    script {
                        echo result.getResult()
                        echo result.getAbsoluteUrl()
                        echo result.getDurationString()
                        
                    }
                }
            }
        }

Upvotes: 1

Jan
Jan

Reputation: 368

If you just want to get the result and know what exact job you are executing you will have that info available via the jenkins api.

Example GET {baseUrl}:{port}/job/{jobName}/job/{branch}/lastBuild/api/json?pretty=true will return a jsonobject with a lot of info, one of the being the result.

You can also do this for lastBuild, lastStableBuild, lastSuccessfulBuild, lastFailedBuild, lastUnstableBuild, lastUnsuccessfulBuild, lastCompletedBuild.

Upvotes: 1

Related Questions