Chris Hansen
Chris Hansen

Reputation: 8645

Grep Jenkins output and email user

How do I grep the Jenkin's output and email the user if the word "Fail" shows up in the output? I want to use Jenkin's pipeline system.

I am running an ssh command using Jenkins. I want at the end of the job to grep the Jenkin's output and send an email to the admin if there are any failures (if the word "Fail" shows up in the output). How can I do that with Pipeline?

Upvotes: 0

Views: 839

Answers (1)

yong
yong

Reputation: 13712

You can use the pipeline step httpRequest to send a http request to the build console url: BUILD_URL/consoleText

You can get the current BUILD_URL via global variable: currentBuild.absoluteUrl or env.BUILD_URL

pipeline {
    agent any

    stages {

        stage('test') {
            steps {

                script {
                    def response = httpRequest([
                           // if your jenkins need login, 
                           // add your jenkins account or a common accout
                           // to jenkins credentials, below authentication value is 
                           // the credential Id
                           authentication: 'ba2e4f46-56f1-4467-ae97-17b356d7f854',

                           url: currentBuild.absoluteUrl + 'consoleText'])

                    if(response.status == 200) {
                        if(response.content =~ /Fail/) {
                            sh 'echo Build fail'
                            // add step to send mail
                        }
                        else {
                            sh 'echo Build successfully'
                        }
                    }
                    else {
                        echo 'Fail to fetch the build console log'
                    }
                } 

            }           
        }        
    }
}

Upvotes: 1

Related Questions