简体   繁体   中英

Jenkins Pipeline | Groovy exception handling

Am writing a Groovy script in Jenkins pipeline, which executes shell script on a remote server. Based on the output of shell script, I should handle the exception.

If shell script output = 'xyz' > Build success

If shell script output != 'xyz' > Throw Exception, build failure.

Any help would be highly appreciated!

My Script

def check()
{
    try 
    {
        println "Check started"
        
        sh "echo -e '' >> Result.txt"
        sh "ssh -q -o StrictHostKeyChecking=no test_agent@Bihkik1123.xyz.com  /home/test_agent/check.sh >> Result.txt"

    
        println "Check completed"
    }
    catch(Exception e) 
    {
       throw e;
    }
}

You can mark the stage as FAILED in case the keyword is not matched for eg. :

  stage('test') {
        println "Check started"
        sh "echo 'xyz' > /tmp/results.txt"
        
        shellReturn = sh(returnStdout: true, script: """
            cat /tmp/results.txt
        """).trim()
        
        if(shellReturn == /xyz/){
          currentBuild.result = 'SUCCESS'      
        } else{
          println "FAILED"
          currentBuild.result = 'FAILED'
        }
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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