jenkins - 如何根据执行结果在 Jenkins Pipeline 中设置当前构建结果?
问题描述
我编写了以下代码并想向用户发送电子邮件通知。但是我注意到有时会有“误报”报告。我只是想知道 Jenkins 声明式管道是否有一种方法允许我使用真实的执行状态来设置 currentBuild.result。(我想我应该使用currentBuild.result = 'SUCCESS'
or 'FAILURE'
)。例如,start_up.sh /mydata/test.json
可以将“SUCCESSFUL”或“ERROR”写入文件。如何根据该文件的内容将 currentBuild.result 分别设置为“SUCCESS”或“FAILURE”?非常感谢。
pipeline {
agent {
docker {
image ...
args ...
}
}
parameters {
string(name: 'E_USERNANE', defaultValue: 'githubuser', description: 'Please input the username')
string(name: 'E_BRANCH', defaultValue: 'dev', description: 'Please input the git branch you want to test')
}
stages {
stage('build') {
steps {
echo "username: ${params.E_USERNANE}"
echo "branch: ${params.E_BRANCH}"
sh """
...
start_up.sh /mydata/test.json
...
"""
}
}
}
post {
failure {
// notify users when the Pipeline fails
mail to: 'xxxi@gmail.com',
subject: "Failed Pipeline * ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}."
}
success {
// notify users when the Pipeline succeeds
mail to: 'xxx@gmail.com',
subject: "Success Pipeline * ${currentBuild.fullDisplayName}",
body: "The build ${env.BUILD_URL} is passed!"
}
}
}
解决方案
看起来标题(如何根据执行结果在 Jenkins 管道中设置当前构建结果?)与代码示例(如何将 currentBuild.result 分别设置为 'SUCCESS' 或 'FAILURE',根据该文件的内容?)
在像您这样的声明式管道中,可以根据使用catchError
block 的命令执行结果轻松设置当前构建(和阶段)结果。例如,将舞台设置为FAILURE
,将整体工作设置为UNSTABLE
:
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
command ...
}
我不知道直接从文件内容(来自正文的问题)设置构建/阶段结果的优雅单行。但我想您可以(并且应该)start_up.sh
在将状态消息写入文件时设置脚本的正确退出代码。因此,在写入"SUCCESSFUL"
文件时,您可以使用零代码退出脚本,但在写入时,"ERROR"
您可以使用非零代码退出。catchError
如上所述,这足以使管道与块一起工作。
推荐阅读
- kubernetes - Kubernetes 节点重启后 Cassandra pod 失败
- c# - .Net core web api 在调用 Startup 之前配置服务
- regex - 如何从速度模板中的字符串中提取字母和数字序列?
- reactjs - 触发 useEffect 生命周期 (componentdidmount) 后 clear 方法将立即调用
- javascript - Eslint 对象属性换行不起作用
- if-statement - 如何解析 Http json 响应并基于此失败或传递作业?
- arrays - 有没有办法在批处理脚本中动态设置数组索引
- javascript - Chrome 扩展程序 - 为什么某些与过滤器不匹配的 url 仍然通过?
- python - 如何打开终端,在其上执行 python 脚本,然后等待脚本结束?
- sql - 相对于固定手动列值条件的列的总和