Andrey Regentov
Andrey Regentov

Reputation: 3737

Jenkins pipeline: fail build on string found in build console

Using jenkins pipeline, I want to fail build when a word (for example, "FATAL") is found in build log.

There is a Text Finder plugin that can do it in freestyle jobs, but one cannot use it in pipelines.

Upvotes: 0

Views: 7102

Answers (2)

Joerg S
Joerg S

Reputation: 5129

You can use the Log Parser Plugin which also support Jenkins Pipeline jobs. It's working for us.

Global Rules

We configured some global rules in Manage Jenkins->Configure System->Console Output Parsing. The files configured there are placed at a location accessible to the Jenkins Master, e.g.

# /home/jenkins/default.rules (on the jenkins master machine)
error /ERROR/

E.g. having a rule set called 'default' which refers to /home/jenkins/default.rules' you could use the following (theparsingRulesPathyou can get using the snippet generator selectingdefault` rules):

echo "ERROR: Some error"
node {
    step([$class: 'LogParserPublisher',
        failBuildOnError: true,
        parsingRulesPath: '/home/jenkins/default.rules',
        useProjectRule: false])
}

Project Rules

Turns out that there's no need to have a global configuration entry. You may also use rules located in your workspace, like:

echo "ERROR: Some error"
node {
    // Usually I assume a project rules file will be stored in
    // some repository and are not generated on the fly
    writeFile(file: 'project.rules', text:
'''
error /ERROR/
''')
    step([$class: 'LogParserPublisher',
        failBuildOnError: true,
        projectRulePath: 'project.rules',
        useProjectRule: true])
}

Although the examples above are for scripted pipeline it should be easy to apply them to declarative pipeline as well.

Upvotes: 1

Andrey Regentov
Andrey Regentov

Reputation: 3737

This works

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh '''
                    echo Blabla
                    echo FATAL error
                '''
            }
        }

        stage('Results') {
            steps {
                script {
                    def logz = currentBuild.rawBuild.getLog(10000);
                    def result = logz.find { it.contains('FATAL') }
                    if (result) {
                        error ('Failing due to ' + result)
                    }
                }
            }
        }
    }
}

But requires several script approvals from Jenkins admins.

And there is an approval request that states "Approving this signature may introduce a security vulnerability! You are advised to deny it."

Upvotes: 0

Related Questions