简体   繁体   English

在Groovy中使用grep进行if if else语句高级

[英]Advanced if else statements with grep in Groovy

I have following Jenkinsfile which will grep for a string from URL, it will send a notification to Slack depends upon the output. 我有下面的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"""
         }
       }
    }

Absolutely the slackSend notification won't work, as it is a plugin. 绝对slackSend通知将不起作用,因为它是一个插件。 I am looking for ways to do the same in Groovy so that I can implement slackNotification. 我正在寻找在Groovy中执行相同操作的方法,以便可以实现slackNotification。

I tried the following logic in Groovy, as an example. 作为示例,我在Groovy中尝试了以下逻辑。 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
     }
       }

}}

You can just use Groovy's (to be more accurate Java's) .contains(String) method to check if some string contains other string. 您可以只使用Groovy(更准确地说是Java)的.contains(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
     }
   }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM