HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to mark build success when one of the stages is aborted?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
thehowsuccessstagesonewhenbuildabortedmark

Problem

I've a pipeline with stages where one of the stage, intermittently takes longer than expectation and hence using timeout to abort it. But if the stage is aborted, build also marked as aborted. Following is the code for pipeline -

pipeline {
    agent any

    stages {

        stage('First') {
            options {
                timeout(time: 10, unit: 'SECONDS')
            }
            steps {
                script {

                    catchError(buildResult: 'SUCCESS') {
                        echo "Executing stage I"
                        sleep 12
                    }

                }
            }
        }

        stage('Second') {
            steps {
                script {
                    echo "Executing stage II"
                }
            }
        }
    }
}


Even though the stage is marked as Aborted, I want to mark build as Success. Can you please help how I can achieve this?

Solution

I answered that question stackoveflow and I'll post the answer here:

For a Declarative pipeline (not a scripted) you would do something like this

stage('Foo') {
      steps {
            script {
                env.PROCEED_TO_DEPLOY = 1
                try {
                    timeout(time: 2, unit: 'MINUTES') {
                        // ...
                    }
                } catch (err) {
                    env.PROCEED_TO_DEPLOY = 0
                }
            }
      }
  }
  stage('Bar') {
    when {
        expression {
            env.PROCEED_TO_DEPLOY == 1
        }
    }
    //rest of your pipeline


stage "Bar" would be skipped but as for the rest of the stages the job will be marked as passed (assuming nothing wrong happened before).

As for your particular use-case, the trick is to use a try/catch block.

Code Snippets

stage('Foo') {
      steps {
            script {
                env.PROCEED_TO_DEPLOY = 1
                try {
                    timeout(time: 2, unit: 'MINUTES') {
                        // ...
                    }
                } catch (err) {
                    env.PROCEED_TO_DEPLOY = 0
                }
            }
      }
  }
  stage('Bar') {
    when {
        expression {
            env.PROCEED_TO_DEPLOY == 1
        }
    }
    //rest of your pipeline

Context

StackExchange DevOps Q#11346, answer score: 2

Revisions (0)

No revisions yet.