Clean-up, notifications and test reports must happen even when the build fails, and that is exactly what post does.
A post section runs after the pipeline or after a single stage, in blocks chosen by the result:
always: whatever happened.success,failure,unstable,aborted: on that result.changed,fixed,regression: compared with the previous build, useful for notifications only when something changes.cleanup: last of all, after the other post conditions.
Build results in Jenkins are SUCCESS, UNSTABLE (typically: tests failed but the build ran), FAILURE and ABORTED.
Two steps belong in almost every pipeline's post:
junit 'reports/*.xml'parses JUnit XML test reports, shows trends and failing tests in the UI, and marks the build UNSTABLE when tests fail.archiveArtifacts artifacts: 'dist/**', fingerprint: truestores files with the build so people and other jobs can download them.
Workspaces persist on agents between builds, so leftovers from earlier runs can leak in; cleanWs() (Workspace Cleanup plugin) or deleteDir() in post { cleanup { } } avoids that.
Also set a build discarder (covered with options) so stored artifacts and logs don't fill the controller's disk.
Example
pipeline {
agent any
stages {
stage('Test') {
steps { sh './gradlew test' }
post {
always { junit 'build/test-results/test/*.xml' }
}
}
stage('Package') {
steps { sh './gradlew assemble' }
}
}
post {
success { archiveArtifacts artifacts: 'build/libs/*.jar', fingerprint: true }
failure { echo "Build ${env.BUILD_NUMBER} failed: ${env.BUILD_URL}" }
fixed { echo 'Back to green' }
cleanup { deleteDir() } // wipe the workspace last
}
}Remember
- post blocks: always, success, failure, unstable, changed, fixed, cleanup
- junit publishes test results and marks failures UNSTABLE
- archiveArtifacts keeps build outputs with the build
Watch out for
- Putting junit inside steps after the test command: if tests fail, the step never runs. Use post { always }.