Groovy 中使用 grep 的高级 if else 语句
Advanced if else statements with grep in Groovy
我有以下 Jenkinsfile,它将从 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
}
}
}}
您可以只使用 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
}
}
}
}
我有以下 Jenkinsfile,它将从 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
}
}
}}
您可以只使用 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
}
}
}
}