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?

1

4 Answers 4

20

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

1
  • 4
    If you use a docker container as an agent, this won't run the post within the container :(
    – djsumdog
    Mar 21, 2018 at 16:10
10
   try {
         sh "false"
    } finally {

        stage 'finalize'
        echo "I will always run!"
    }
2
  • how do you do this in a pipeline script? Oct 31, 2017 at 18:03
  • @AndrewMyhre that is pipeline script syntax so you can copypaste that into your pipeline definition.
    – jjmontes
    Aug 19, 2019 at 16:01
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.

2
  • 1
    The order in which these steps will be executed might be random.
    – M. Niklas
    Jul 1, 2022 at 8:52
  • 1
    I checked some runs, and they all execute the stages in order of the Jenkinsfile
    – hintze
    Jul 4, 2022 at 6:59
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'
        }
    }
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.