我想在管道Jenkins作业中获取最后一个构建输出并附加到电子邮件中(使用emailext插件)。 Curl工作正常并提供正确的构建输出,但我无法存储在变量中以附加到电子邮件中。我使用的是最新的詹金斯版本。
我可以看到有几个简单的sh命令的相关帖子,但这对卷曲响应存储不起作用。
1
def consoleOutput = sh(returnStdout: true, script: 'curl http://' + jenkinsUser + ':' + jenkinsUserToken + '@' + jenkinsServer + ':8080/job/' + 'myJob/lastBuild/consoleText').trim()
echo consoleOutput
2
sh 'curl http://' + jenkinsUser + ':' + jenkinsUserToken + '@' + jenkinsServer + ':8080/job/' + "${env.JOB_NAME}" + '/lastBuild/consoleText; echo $? > status'
def consoleOutput = readFile('status').trim()
3
def consoleOutput = sh(script: 'curl http://' + jenkinsUser + ':' + jenkinsUserToken + '@' + jenkinsServer + ':8080/job/' + '/myJob/lastBuild/consoleText', returnStatus: true).split("\r?\n")
echo consoleOutput
答案 0 :(得分:4)
看起来你错过了内部数组和一些双引号并转义了双引号来运行脚本:
sh([ script: "curl \"http://${jenkinsUser}:${jenkinsUserToken}@${jenkinsServer}:8080/job/myJob/lastBuild/consoleText\"").trim()
还有多种方法可以执行shell脚本,它取决于您使用的 jenkins管道类型。
在jenkins declarative pipeline中,您需要为所有脚本类型代码和设置变量添加script {...}
块,如下所示:
pipeline {
agent {
...
}
parameters {
...
}
environment {
...
}
stages {
stage('Run Required Scripts') {
steps {
...
script {
NOTIFIER_BULD_NAME = sh([script: "./getNotifier.sh", returnStdout: true]).trim()
EMAIL_TEXT = sh([script: "./printEmailText.sh ${CURRENT_BUILD} ${PREVIOUS_BUILD}", returnStdout: true]).trim()
BODY= sh([ script: "curl \"http://${jenkinsUser}:${jenkinsUserToken}@${jenkinsServer}:8080/job/myJob/lastBuild/consoleText\"").trim()
}
}
}
stage('Send Email') {
when {
expression {
// Only send when there is text.
"${EMAIL_TEXT}" != "";
}
}
steps{
emailext (
to: 'software@company.com',
subject: "You have mail - ${EMAIL_TEXT}",
body: """${NOTIFIER_BULD_NAME} - ${EMAIL_TEXT}:
...
${BODY}
""",
attachLog: false
)
}
}
}
在Jenkins scripted pipeline中,您不需要script{}
块,实际上您可以将其置于大多数位置。大多数情况下,我把它放在舞台块stage('some stage'){...}
中,我就这样做了:
V5_DIR = WORKSPACE + '/' + sh([script: "basename ${V5_GIT_URL} .git", returnStdout: true]).trim()
虽然我也使用了curl命令(对于脚本化的管道)而且不需要内部数组...
lastSuccessfulCommit = sh(
script: "curl -sL --user ${JENKINS_API_USER}:${JENKINS_API_PSW} \"${lastSuccessfulCommitUrl}\" | sed -e 's/<[^>]*>//g'",
returnStdout: true
)
作为参考,回声变量在两者中都是这样的
sh([script: "echo \"Value: ${someVariable}\""])
希望this documentation有点帮助,但我知道最近詹金斯的文档可能非常不稳定,所以我也找到了a great gist about how to not do things for Jenkins Declarative pipelines。祝你好运!