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