Reputation: 2345
I have following Jenkinsfile which will grep for a string from URL, it will send a notification to Slack depends upon the output.
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"""
}
}
}
Absolutely the slackSend notification won't work, as it is a plugin. I am looking for ways to do the same in Groovy so that I can implement slackNotification.
I tried the following logic in Groovy, as an example. But it didn't work, as even if the line is not present is is printing line is found.
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
}
}
}}
Upvotes: 1
Views: 2534
Reputation: 4628
You can just use Groovy's (to be more accurate Java's) .contains(String) method to check if some string contains other string. Also when you execute command in pipeline you can capture stdout of that command.
Code:
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
}
}
}
}
Upvotes: 2