Robert Munteanu
Robert Munteanu

Reputation: 68268

Get the cause of a Maven build failure inside a Jenkins pipeline

I have a Jenkins scripted pipeline set up where I execute a number of Maven builds. I want to treat one of them as non-fatal if the root cause is a known one.

I have tried to achieve that by inspecting the Exception's message, e.g.

try {
    sh "mvn -U clean verify sonar:sonar ${sonarcloudParams}"
} catch ( Exception e ) {
    if ( e.getMessage().contains("not authorized to run analysis")) {
        echo "Marking build unstable due to missing SonarCloud onboarding. See https://cwiki.apache.org/confluence/display/SLING/SonarCloud+analysis for steps to fix."
        currentBuild.result = 'UNSTABLE'
    }
}

The problem is that the exception's message is not the one from Maven, but instead "script returned exit code 1".

There is no further information in e.getCause().

How can I access the cause of the Maven build failure inside my scripted pipeline?

Upvotes: 3

Views: 2128

Answers (2)

yong
yong

Reputation: 13712

You can get the command output, then parse it containers specific message.

def output = sh(
        script: "mvn -U clean verify sonar:sonar ${sonarcloudParams}",
        returnStdout: true
    ).trim()

echo "mvn cmd output: ${output}"

if(output.contains('not authorized to run analysis')) {
    currentBuild.result = 'UNSTABLE'
}


// parse jenkins job build log
def logUrl = env.BUILD_URL + 'consoleText'

def cmd = "curl -u \${JENKINS_AUTH} -k ${logUrl} | tail -n 50"

def output = sh(returnStdout: true, script: cmd).trim()

echo "job build log: ${output}"

if(output.contains('not authorized to run analysis')) {
    currentBuild.result = 'UNSTABLE'
}

Upvotes: 3

Robert Munteanu
Robert Munteanu

Reputation: 68268

One option is to inspect the last log lines using

def sonarCloudNotEnabled = currentBuild.rawBuild.getLog(50).find { 
    line -> line.contains("not authorized to run analysis") 
}

However, this does not work by default. On the Jenkins instance I'm using it errors out with

Scripts not permitted to use method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild. Administrators can decide whether to approve or reject this signature.

Upvotes: 1

Related Questions