16

I am looking for a Jenkinsfile example of having a step that is always executed, even if a previous step failed.

I want to assure that I archive some builds results in case of failure and I need to be able to have an always-running step at the end.

How can I achieve this?

sorin
  • 161,544
  • 178
  • 535
  • 806

4 Answers4

19

We switched to using Jenkinsfile Declarative Pipelines, which lets us do things like this:

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                sh './gradlew check'
            }
        }
    }
    post {
        always {
            junit 'build/reports/**/*.xml'
        }
    }
}

References:

Tests and Artifacts

Jenkins Pipeline Syntax

m0j0hn
  • 532
  • 4
  • 16
10
   try {
         sh "false"
    } finally {

        stage 'finalize'
        echo "I will always run!"
    }
sorin
  • 161,544
  • 178
  • 535
  • 806
1

Another possibility is to use a parallel section in combination with a lock. For example:

pipeline {
    stages {
        parallel {
            stage('Stage 1') {
                steps {
                    lock('MY_LOCK') {
                        echo 'do stuff 1'
                    }
                }
            }
            stage('Stage 2') {
                steps {
                    lock('MY_LOCK') {
                        echo 'do stuff 2'
                    }
                }
            }
        }
    }
}

Parallel stages in a parallel section only abort other stages in the same parallel section if the fail fast option for the parallel section is set. See the docs.

hintze
  • 544
  • 2
  • 13
0

When a Jenkins stage fails, all of the rest starts and ignore message. So stages are skipped but you really want them to run. You can use the catchError block to catch errors and continue with the pipeline. Here’s an example:

stage('Example') {
    steps {
        catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
            sh './run-my-script.sh'
        }
    }
}
p K
  • 71
  • 1
  • 2