Jenkinsfile - get gradle build message in case of exception - jenkins

I want to get the error message in case a grade build fails and send it over slack.
In Jenkinsfile I have:
Jenkins build console output says:
+ ./gradlew build -x test -x integrationTest
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':spotlessJavaCheck'.
The following files had format violations:
src/main/java/com/src/Test.java
## -1241,7 +1241,7 ##
········.flatMap(x -> x.getStream().stream())
········.filter(x·->·x.getSize() > 9)
··}
··public·String·getMessage()·{
I tried like:
stage('Build the project') {
/* sh "./gradlew clean classes" */
stageName = env.STAGE_NAME
def message
try {
message = sh(returnStdout: true, script: "./gradlew build -x test -x integrationTest")
} catch(Exception buildException){
echo "Build exception is " + message
throw buildException
}
}
But I get
Build exception is null
I tried also like:
try{
stage('Build the project') {
/* sh "./gradlew clean classes" */
stageName = env.STAGE_NAME
sh "./gradlew build -x test -x integrationTest"
}
} catch (Exception ex) {
echo "We received " + ex.toString()
But it's logging:
We received hudson.AbortException: script returned exit code 1
How can I get the message of the gradle build into a variable?
I want to use that so that I can send it to slack in a message and not always go to jenkins build

Try to redirect stderr to stdout:
message = sh(returnStdout: true, script: "./gradlew build -x test -x integrationTest 2>&1")

Related

step not run in jenkins pipeline, and exit code -2

Result:
npm config set registry https://registry.npm.taobao.org
npm config set 'sass-binary-site=http://npm.taobao.org/mirrors/node-sass'
process apparently never started in /home/jenkins/workspace/demo_nodejs#tmp/durable-a15f6a06
ERROR: script returned exit code -2
Finished: FAILURE
And there is my Pipeline script(SECRET is my secret message):
def registry = SECRET
def library = 'demo'
def name = 'nodejs_demo'
podTemplate(){
node('nodejs') { // my podtemplate is defined in global config, and can run well.
echo 'ready go'
def path = pwd()
def branch_ = ''
def author = ''
def version = ''
def image
branch_ = 'master'
echo 'branch_ = ' + branch_
// clone git
stage("clone code") {
git credentialsId: SECRET, branch: branch_, url: SECRET
sh 'git log --no-merges --pretty=format:"%an" -1 > author.txt'
sh 'git log --no-merges --pretty=format:"%h" --abbrev=8 -1 > version.txt'
sh 'url=`cat .git/config|grep git`&&url=${url##*/}&&echo ${url%.*} > name.txt'
author = readFile("author.txt")
version = readFile("version.txt")
image = "${registry}/${library}/${name}"
echo "${image}"
echo 'clone code complete'
}
# enter container.
container('nodejs') {
stage("nodejs install") { // my Step
sh 'npm config set registry https://registry.npm.taobao.org'
sh 'npm config set sass-binary-site=http://npm.taobao.org/mirrors/node-sass'
sh 'npm install' // not execute it.
}
stage("nodejs build") {
sh 'npm run build'
}
stage('copy dockerfile') {
input "Exit"
}
}
}
}
Status:
"npm install" or "npm build" is defined in my jenkinsfile.
When script run "npm config" In my jenkinsfile, the next step is "npm install", but it was not run, and my workflow is exit.
I use same jenkinsfile, I can receive success message if I am full luck.
The Error will be occur in other location, example after "npm install" or after "npm build" and soon.
Please check if you have an empty environment variable in your global configuration or node configuration.

why jenkins job is not failing - even if npm script fails in stage?

I have following Jenkinsfile:
stage('build mod') {
steps {
dir("cli") {
script {
try {
sh('node index.js -m shell -h project -p max4 -i local')
} catch (Exception e) {
currentBuild.result = 'FAILURE'
throw e
}
}
}
}
}
The script fails:
ERROR Build failed with errors.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/jenkins/.npm/_logs/-debug.log
But the stage passes with green... Why try-catch did not work in this case?
First and foremost you need to understand that even though the code inside of the script failed, the shell function that jenkinsfile had called was successful. That's wht jenkinsfile couldn't catch the error as the script returned 0. So you need to write a code that will catch the return value of the code executing inside that of the script. Something similar to
result = sh (
script: "node index.js -m shell -h project -p max4 -i local",
returnStatus: true
)
if (result != 0) {
currentBuild.result = 'FAILURE'
break
}
Here "break" is very important as we don't want other stages to get executed once build has failed.

What is a rule to make target in Docker container?

To learn how to manipulate Docker images from within Jenkins, I am reading this link.
What is a "rule to make a target" in Docker? The simple example below is failing because there is "no rule to make a target". What does this mean in Docker?
The Error And The Code That Triggers The Error
The sh 'make test' line of code in a Jenkinsfile from the link above is throwing an error when run inside the following block:
testImage.inside {
sh "whoami"
sh 'make test'
}
The actual error that Jenkins throws when trying to interpret the sh 'make test' line of code is:
make test— Shell Script<1s
[ple-dockere-containered-app-WWNVRTE6XFKMI4JPEVK2F2U3HOGDZICATW6XBFM2IQUW5PAG5FWA] Running shell script
+ make test
make: *** No rule to make target 'test'. Stop.
The complete Jenkinsfile is:
node {
// Clean workspace before doing anything
deleteDir()
try {
stage ('Clone') {
checkout scm
}
stage ('Build') {
def testImage = docker.build("test-image", "./app")
testImage.inside {
sh "whoami"
sh 'make test'
}
}
} catch (err) {
currentBuild.result = 'FAILED'
throw err
}
}
Note that the make test command is being run inside the container.

How to combine newman collection test results into one valid xml file for Jenkins?

I've got a small Jenkins pipeline which tests different Postman collections sequentially and after that I combine the single XML files into one to pass them to Jenkins as a result.
Pipeline snippet:
...
steps {
script {
try {
sh '(cd ./integrativeTests/collections && rm -rf *.xml)'
sh '(cd ./integrativeTests/collections && npm run tests-all)'
sh '''
cd ./integrativeTests/collections
echo '<?xml version="1.0" encoding="UTF-8"?>' > newman_dev_results.xml
echo '<testsuites>' >> newman_dev_results.xml
for f in COLLECTION-*.xml
do
echo $(sed 1,$(expr $(grep -m1 -n "<testsuite" ${f} | cut -f1 -d:) - 1)d ${f}) >> newman_dev_results.xml
done
echo '</testsuites>' >> newman_dev_results.xml
cat newman_dev_results.xml
'''
sh '(cp ./integrativeTests/collections/newman_dev_results.xml ./newman_results.xml)'
currentBuild.result = 'SUCCESS'
} catch(Exception e) {
currentBuild.result = 'FAILURE'
}
junit 'newman_results.xml'
}
}
...
The resulting XML looks like this:
But sadly I get an ERROR in the Jenkins log:
ERROR: None of the test reports contained any result
Finished: FAILURE
What's the correct xml-layout for a test result with multiple collections for Jenkins or how do I pass multiple test results to Jenkins?
As found in the official docs of the Junit Plugin I don't need to combine all xml by myself and pass a single file. I just need to pass all XMLs at once with a wildcard.
Pipeline:
...
steps {
script {
try {
sh '(cd ./integrativeTests/collections && npm run tests-all)'
currentBuild.result = 'SUCCESS'
} catch(Exception e) {
currentBuild.result = 'FAILURE'
}
sh 'junit-viewer --results=./integrativeTests/collections --save=result.html'
archiveArtifacts artifacts: 'result.html', fingerprint: true
junit '**/integrativeTests/collections/COLLECTION-*.xml'
}
}
...

Jenkins Pipeline Error

I am using the pipeline plugin in Jenkins, but unable to run shell commands. I am receiving the following error:
[develop - pipeline] Running shell script
nohup: failed to run command ‘sh’: No such file or directory
The node is an Ubuntu instance.
node ('aws-ondemand') {
//println env.BUILD_NUMBER
try {
stage 'Checkout and Build'
git url: 'git#github.com:MyAndroidRepo.git',
branch: 'develop'
sh 'git submodule init'
sh 'git submodule update'
sh './gradlew clean build'
}catch (e) {
//currentBuild.result = "FAILED"
//notifyFailed()
throw e
}
}
Nevermind. Script is fine. I was injecting env variables in the build step. I removed it and now its working.

Resources