Hi community!
In my declarative pipeline I’m trying to get the information if my branch has changes since my last Jenkins build. I was able to achieve that using currentBuild.changeSets.size() > 0
, but with this approach I’m not able to share this information in a variable, so that I can also reuse it in my post section.
Here is my example code.
def changeCount = 0
pipeline {
environment {
BACKUP_FILE = "${'backup_' + env.BUILD_ID + '_tar.gz'}"
DEPLOY_FOLDER = "${'deploy' + env.BUILD_ID}"
}
agent none
stages {
stage ("Check changes") {
steps {
echo "Check if there are any changes pushed into this branch..."
script {
changeCount = currentBuild.changeSets.size()
}
echo "${changeCount} commit(s) since last buid."
}
}
stage('start process') {
matrix {
agent {
label 'mylabel'
}
axes {
axis {
name 'AGENTS'
values 'agent1', 'agent2'
}
}
stages {
stage('PREPARE ENVIRONMENT') {
when {
expression {
changeCount > 0
}
}
steps {
sh '''
...
'''
}
}
stage('Build') {
when {
expression {
changeCount > 0
}
}
steps {
sh '''
...
'''
}
}
stage('Test') {
when {
expression {
changeCount > 0
}
}
steps {
sh '''
...
'''
}
}
stage('Deploy') {
when {
expression {
changeCount > 0
}
}
steps {
sh '''
...
'''
}
}
}
}
}
}
post {
always {
script {
if (currentBuild.changeSets.size() > 0) {
emailext (
attachLog: true,
compressLog: true,
to: 'myemail@domain.com;',
subject: "Application - Build # ${BUILD_NUMBER}",
body: "Status: ${currentBuild.currentResult}\nBuild number: ${env.BUILD_NUMBER}\nTo see log details open the attached file or click on the link: ${env.BUILD_URL}"
)
} else {
emailext (
attachLog: false,
compressLog: false,
to: 'myemail@domain.com;',
subject: "Application - Build # ${BUILD_NUMBER}",
body: "There are no changes pushed since last build."
)
}
}
}
}
}
Questions:
- How can I update the variable
changeCount
and reuse it in mypost section
? - Is there a better way of achieving the same outcome?
- I also tried to actually create a variable for the email body content, and update this variable according to the changeCount variable, and then use the variable in my
emailtext command
. I tried to declare a local variable, but it didn’t work well. Any suggestions on that? - It seems that when using matrix I’m not able to retrieve the number of changes. How can I get this information with this approach?
- Is it possible to prevent the SCM checkout from happening in case there are no changes in my branch?
Thank you very much in advance.
Best regards,
Alex