Console output validation in jenkins stage

Viewed 26

In our pipeline job , we have few stages

eg: this stage will start the automation job

stage('Run E2E tests') {
     steps {
        withCredentials([
          sshUserPrivateKey(credentialsId: 'XXXXX', keyFileVariable: 'SSH_KEY_FILE', usernameVariable: 'SSH_USER')
         ]) {
        sh """
            eval `ssh-agent -s`
            ssh-add ${SSH_KEY_FILE}
            ~/earthly \
              --no-cache \
              --config=.earthly/config.yaml \
              +e2e
            eval `ssh-agent -k`
          """
        }
      } 
    }

I am planning to add one more stage with validate the console out put like below

stage("Check Test Case Results"){
      steps {
      script{
        if (manager.logContains('.*myTestString.*')) {
          error("Build failed because of this and that..")    
        }else{
echo("No issues")
}
      }
      }

  }

But above stage is not validating the if condition always going to else statement.

1 Answers

This is coming from a third-party plugin. And you need to execute your logic in a Post stage. The following seems to work for me.

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
               echo "myTestString"
            }

            post {
                always {
                    script {
                        if (manager.logContains('.*myTestString.*')) {
                          error("Build failed because of this and that..")    
                        }else{
                            echo("No issues")
                        }
                    }
                }
            }
        }
    }
}

Also, you can do this without third-party Plugins as well. Here is the solution without the plugin. You can execute this at any point in the Pipeline.

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
               echo "myTestXString"
            }

            post {
                always {
                    script {
                        def consoleLog = Jenkins.getInstance().getItemByFullName(env.JOB_NAME).getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER)).logFile.text
                        if (consoleLog.contains('myTestString')) {
                          error("Build failed because of this and that..")    
                        }else{
                            echo("No issues")
                        }
                    }
                }
            }
        }
    }
}
Related