问题
Have a Jenkins pipeline. Need/want to send emails when build succeeds. Email about all branches to maillist-1 and filter builds of master branch to maillist-master.
I tried using if
and when
statements-steps but both of them fail in post block.
pipeline {
agent ...
stages {...}
post{
success{
archiveArtifacts: ...
if( env.BRANCH_NAME == 'master' ){
emailext( to: 'maillist-master@domain.com'
, replyTo: 'maillist-master@domain.com'
, subject: 'Jenkins. Build succeeded :^) 😎'
, body: params.EmailBody
, attachmentsPattern: '**/App*.tar.gz'
)
}
emailext( to: 'maillist-1@domain.com'
, replyTo: 'maillist-1@domain.com'
, subject: 'Jenkins. Build succeeded :^) 😎'
, body: params.EmailBody
, attachmentsPattern: '**/App*.tar.gz'
)
}
}
}
How wanted behavior could be achieved?
回答1:
It's true you currently can't use when
in the global post block. When
must be used inside a stage directive.
It's a logical choice to use if else
, but you'll need a scripted block inside the declarative pipeline to make this work:
pipeline {
agent any
parameters {
string(defaultValue: "master", description: 'Which branch?', name: 'BRANCH_NAME')
}
stages {
stage('test'){
steps {
echo "my branch is " + params.BRANCH_NAME
}
}
}
post {
success{
script {
if( params.BRANCH_NAME == 'master' ){
echo "mail list master"
}
else {
echo "mail list others"
}
}
}
}
}
Output when parameter is master:
[Pipeline] {
[Pipeline] stage
[Pipeline] { (test)
[Pipeline] echo
my branch is master
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
mail list master
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
output when parameter is 'test':
[Pipeline] {
[Pipeline] stage
[Pipeline] { (test)
[Pipeline] echo
my branch is test
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
mail list others
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Or to make it even more clean you can call the script as a function:
pipeline {
agent any
parameters {
string(defaultValue: "master", description: 'Which branch?', name: 'BRANCH_NAME')
}
stages {
stage('test'){
steps {
echo "my branch is " + params.BRANCH_NAME
}
}
}
post {
success{
getMailList(params.BRANCH_NAME)
}
}
}
def getMailList(String branch){
if( branch == 'master' ){
echo "mail list master"
}
else {
echo "mail list others"
}
}
来源:https://stackoverflow.com/questions/49559882/jenkins-declarative-pipeline-conditional-statement-in-post-block