我正在尝试将变量值从一个阶段传递给jenkins的邮件正文。但是变量值不能反映出来。
如果我创建另一个阶段并调用变量,该代码将起作用。但不是在 notifyStatusChangeViaEmail方法块
下面是示例代码。
def variable
pipeline {
agent { label 'master' }
options {
timestamps()
timeout(time: 1, unit: 'HOURS' )
}
stages{
stage('Variable'){
steps {
script{
variable = "Hi, Build is successful"
}
}
}
}
}
def notifyStatusChangeViaEmail(prevBuild) {
def subject
def body
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
case 'UNSTABLE':
emailext attachLog: true, body: "${variable}", recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status : Build is back to Normal', to: 'sumith.waghmare@gmail.com';
break
case 'SUCCESS':
emailext attachLog: true, body: "${variable}", recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status', to: 'sumith.waghmare@gmail.com';
break
}
}
}
答案 0 :(得分:0)
问题在于该变量未在函数范围内定义(this post解释了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
//...
}
}
}
使用变量作为参数: