Introduction
It’s a sample of how to do post build using pipeline inside jenkins.
In some builds, we want to run codes after build. Some times you need run if job fail, or success, or always.
Explanation when use post build
First, let’s do some pipeline
pipeline {
agent any
stages {
stage('Error') {
steps {
error "failure test. It's work"
}
}
stage('ItNotWork') {
steps {
echo "is not pass here"
echo "You can't do post build in other stage"
}
}
}
}
This pipeline have two stages, ‘Error’ and ‘ItNotWork’.
The first stage will get error and the second stage will not run.
If you need a code to run after build, you can put in post build.
pipeline {
agent any
stages {
stage('Error') {
steps {
error "failure test. It's work"
}
}
stage('ItNotWork') {
steps {
echo "is not pass here"
}
}
}
post {
success {
mail to: team@example.com, subject: 'The Pipeline success :('
}
}
}
Eteps in post build
In Post Build you have a lot of steps, let’s talk about the two most usefull steps.
Always
If you want to run everytime after your work is finished, you can use the step “always”
pipeline {
agent any
stages {
...
}
post {
always {
echo 'I will always execute this!'
}
}
}
Failure
If you want execute some code only if the build fail, you can use the step “failure”
pipeline {
agent any
stages {
...
}
post {
failure {
mail to: team@example.com, subject: 'The Pipeline failed :('
}
}
}
How i can do test in this steps
For study, i created a job to test this steps easely.
pipeline {
environment {
//This variable need be tested as string
doError = '1'
}
agent any
stages {
stage('Error') {
when {
expression { doError == '1' }
}
steps {
echo "Failure"
error "failure test. It's work"
}
}
stage('Success') {
when {
expression { doError == '0' }
}
steps {
echo "ok"
}
}
}
post {
always {
echo 'I will always execute this!'
}
}
}
You can test how work post build only changing the environment “doError”.
Try yourself.
More
More information about “Post” section you can see in Jenkins Documentation
Thanks