shelljenkinsgroovycloudbees

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;
    }
}


Solution

  • 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'
            }
          }