Reputation: 25
I need to check a condition before the job triggers the postbuild action
I could see that post section within the Pipeline supports always, changed, failure, success, unstable, and aborted. as the post build conditions. But i want to check another condition in the post build action. I tried with when{} but it’s not supported in post build action.
pipeline {
agent any
stages {
stage('Example') {
steps {
sh 'mvn --version'
}
}
}
post {
}
}
Upvotes: 2
Views: 10594
Reputation: 64
You can add a script tag inside post build action and can use if() to check your condition
post {
failure {
script{
if( expression ){
//Post build action which satisfy the condition
}
}
}
}
You can also add post build action for a stage in the pipeline also. In that case you can specify the condition in the when
pipeline {
stages {
stage('Example') {
when {
//condition that you want check
}
steps {
}
post { //post build action for the stage
failure {
//post build action that you want to check
}
}
}
}}
Upvotes: 3
Reputation: 30723
As you said. The when
option is not available in the post section. To create a condition you can just create a scripted block inside the post section like in this example:
pipeline {
agent { node { label 'xxx' } }
environment {
STAGE='PRD'
}
options {
buildDiscarder(logRotator(numToKeepStr: '3', artifactNumToKeepStr: '1'))
}
stages {
stage('test') {
steps {
sh 'echo "hello world"'
}
}
}
post {
always {
script {
if (env.STAGE == 'PRD') {
echo 'PRD ENVIRONMENT..'
} else {
echo 'OTHER ENVIRONMENT'
}
}
}
}
}
When the env var of STAGE is PRD it will print PRD ENVIRONMENT
in the post section. If it isn't it will print: DIFFERENT ENVIRONMENT
.
Run with STAGE='PRD'
:
[Pipeline] sh
[test] Running shell script
+ echo 'hello world'
hello world
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
PRD ENVIRONMENT..
Run where STAGE='UAT'
(you can use a parameter instead of a env var of course):
[Pipeline] sh
[test] Running shell script
+ echo 'hello world'
hello world
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
OTHER ENVIRONMENT
[Pipeline] }
[Pipeline] // script
Upvotes: 1