我有下面的Jenkinsfile,它将通过grep来获取URL中的字符串,它将根据输出将通知发送给Slack。
stage('Check if present') {
steps {
script{
sh """
if curl -s http://example.foo.com:9000 | grep -q "ERROR"
then
slackSend channel: '#team', message: "Pipeline has been failed due to due to an error, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
echo "Scan result: ERROR" && exit 1
elif curl -s http://example.foo.com:9000 | grep -q "WARN"
then
slackSend channel: '#team', message: "Pipeline is in WARN state due to a warning, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
fi"""
}
}
}
因为它是一个插件,所以绝对不会发送slackSend通知。 我正在寻找在Groovy中执行相同操作的方法,以便可以实现slackNotification。
作为示例,我在Groovy中尝试了以下逻辑。 但这没有用,因为即使该行不存在也就是找到了打印行。
stage('test logic'){
steps{
script{
if ('curl -s http://example.foo.com:9000'.execute() | 'grep foo'.execute())
println("The line is found")
else {
println("The line is not found")
exit 1
}
}
}}
答案 0 :(得分:1)
您可以只使用Groovy的(更准确地说是Java的).contains(String)方法来检查某个字符串是否包含其他字符串。同样,当您在管道中执行命令时,您可以捕获该命令的标准输出。
代码:
stage('test logic'){
steps{
script{
def commandStdout = sh(returnStdout: true, script: "curl -s http://example.foo.com:9000"
if (commandStdout.contains("foo")) {
println("The line is found")
}else {
println("The line is not found")
exit 1
}
}
}
}