我想在管道Jenkins作业中获得最后的构建输出并附加在电子邮件中(使用emailext插件). Curl工作正常,并提供正确的构建输出,但我不能存储在变量中以附加在电子邮件中.我正在使用最新的jenkins版本.
我可以看到有几个简单的sh命令的相关帖子,但这对curl响应存储不起作用.
试过的代码:
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
看起来你错过了内部数组和一些双引号并转义了双引号来运行脚本:
原文链接:https://www.f2er.com/bash/387119.htmlsh([ script: "curl \"http://${jenkinsUser}:${jenkinsUserToken}@${jenkinsServer}:8080/job/myJob/lastBuild/consoleText\"").trim()
还有多种方法可以执行shell脚本,这取决于您使用的jenkins管道的类型.
在jenkins declarative pipeline中,您需要为所有脚本类型代码和设置变量包含一个脚本{…}块,如下所示:
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中,您不需要脚本{}块,实际上可以将它放在大多数地方.大多数情况下,我把它放在舞台块阶段(‘某个舞台’){…},我这样做了:
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有点帮助,但我知道最近jenkins的文档可能非常参差不齐,所以我也找到了a great gist about how to not do things for Jenkins Declarative pipelines.祝你好运!