Проблема в том, что переменная не определена в области действия функции (и в этом посте объясняется, как область действия функций работает в Groovy).
Чтобы исправить возникшую проблему, я бы либо сделал variable
параметром notifyStatusChangeViaEmail
, либо удалил бы оператор def variable
, потому что это сделало бы variable
глобальной переменной, и поэтому функция быть в состоянии получить к нему доступ.
Примеры:
Создание переменной, параметр notifyStatusChangeViaEmail
:
pipeline {
agent { label 'master' }
options {
timestamps()
timeout(time: 1, unit: 'HOURS' )
}
stages {
stage('Send Email') {
steps {
script {
def emailBody = "Hi, Build is successful"
// I assume that prevBuild is defined somewhere already
notifyStatusChangeViaEmail(prevBuild, emailBody)
}
}
}
}
}
def notifyStatusChangeViaEmail(prevBuild, emailBody) {
if (currentBuild.previousBuild != null) {
switch (prevBuild.result) {
case 'FAILURE':
emailext attachLog: true,
body: emailBody,
recipientProviders: [[$class: 'CulpritsRecipientProvider']],
subject: 'Build Status : Build is back to Normal',
to: 'sumith.waghmare@gmail.com';
break
//...
}
}
}
Использование variable
в качестве глобального:
// --> I deleted the "def variable" line <--
pipeline {
agent { label 'master' }
options {
timestamps()
timeout(time: 1, unit: 'HOURS' )
}
stages {
stage('Variable') {
steps {
script {
// There is no "def" when you first assign a value to
// `variable`, so it will become a global variable,
// which is a variable you can use anywhere in your file
variable = "Hi, Build is successful"
}
}
}
}
}
def notifyStatusChangeViaEmail(prevBuild) {
if (currentBuild.previousBuild != null) {
switch (prevBuild.result) {
case 'FAILURE':
emailext attachLog: true, body: variable, recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status : Build is back to Normal', to: 'sumith.waghmare@gmail.com';
break
//...
}
}
}
Использование переменной в качестве параметра: