Jenkinsfile pipeline, return warning but do not fail - jenkins

Is there a way to not fail with a declarative pipeline step but display a warning instead? At the moment I am circumventing it by adding || exit 0 to the end of the sh command lines so it always exits ok.
Example currently:
sh 'vendor/bin/phpcs --report=checkstyle --report-file=build/checkstyle.xml --standard=phpcs.xml . || exit 0'
I feel there should be a better way of doing this? How can you control the result returned so the user knows with out digging through result logs but with out blocking/failing too?
Thank you
Edit:
So I have got this far to be able to mark it as unstable. In Blue Ocean it just marks every stage as unstable though and you have to go digging through to find it. Am I trying to do the impossible (but feels like I should be able to do it)?
Also it just displays it as 'Shell script' in the heading on Blue Sky now instead of showing the command being run so you don't even know what it's doing with out expanding each of them.
script {
def RESULT = sh returnStatus: true, script: 'vendor/bin/phpcs --report=checkstyle --report-file=build/checkstyle.xml --standard=phpcs.xml .'
if ( RESULT != 0 ) {
currentBuild.result = 'UNSTABLE'
}
}
Re marking it all yellow/unstable: Just found this which explains that I am not going mad. Several years of discussion and no progress :( https://issues.jenkins-ci.org/browse/JENKINS-39203
Re it just showing 'Shell script' now on Blue Ocean view: I'll go and play some more and see if I'm better with || exit 0 or a script block and using echo to display some useful info.

FYI: JENKINS-39203 has been resolved in the meantime.
Instead of setting currentBuild.result = 'UNSTABLE' we use the corresponding basic pipeline step unstable, which also takes a message:
unstable("There are Checkstyle issues")

You can find options for any steps in your jenkins itself under http://jenkins-url/pipeline-syntax/. sh with returnStatus: true can be used to achieve your goal.
sh returnStatus: true, script: 'ls -2' # returnStatus: true, just set $? but not fail the execution
Below pasted the screenshot from pipeline-syntax page:

Related

Jenkinsfile shell command not using env variables as expected

In my Jenkinsfile I want to dynamically find the unity version using a python script like so:
environment {
UNITY_EDITOR = bat(script: "py $WORKSPACE/get_versions.py --unity", returnStdout: true).trim()
UNITY_BASE = "C:/Program Files/Unity/Hub/Editor/$UNITY_EDITOR/Editor/Unity.exe"
UNITY_WRAPPER = "UnityBatchWrapper -silent-crashes -no-dialogs -batchmode -quit -unityPath \"$UNITY_BASE\""
}
post {
always {
script {
echo "Returning license"
licenseReturnStatus = bat (
script: "$UNITY_WRAPPER -returnlicense",
returnStatus: true
) == 0
}
}
From other stackoverflow answers this seems like it should work, but instead my Jenkins job errors out during the post-build step because $UNITY_WRAPPER isn't defined:
groovy.lang.MissingPropertyException: No such property: UNITY_WRAPPER for class: groovy.lang.Binding
I'm thinking the batch step is what's failing, even though Jenkins doesn't complain about it. I've also tried using $env.WORKSPACE and %WORKSPACE% and that doesn't work either.
I'm beginning to think $WORKSPACE doesn't exist til after the environments step...
Turns out I didn't have Python installed since it was an ephemeral GCP builder and I hadn't updated the node label yet.
For anyone reading this that has trouble with bat commands - be sure to put an # sign in front of your command like "#py ..." or else the command will be echoed in the output. Also trim your output so it doesn't have CRLF in it.

Jenkins scripted pipeline - sh return nonzero exit code but stage SUCCEEDS

In my Jenkins scripted pipeline, I have a build stage that has the following sh command:
def buildcmd = "./scriptname.sh"+ <paramters>
def status = sh returnStatus: true, script:"""cd /to/some/dir
eval ${buildcmd}
"""
if(status != 0)
{
error("Failure")
}
After execution, scriptname exits with status 2 and status variable also contains 2 and the job fails. But however the stage result is shown as SUCCESS. I expected both the stage result and build result to be FAILURE.
Can anybody please clarify this.
returnStatus (optional)
Normally, a script which exits with a nonzero
status code will cause the step to fail with an exception. If this
option is checked, the return value of the step will instead be the
status code. You may then compare it to zero, for example.
Source
If your goal is to simply let the stage fail use returnStatus: false. Unfortunately I can't tell you the difference between a status code and exit code (like mentioned above). The documentation only tells that if you set returnStatus: true the pipeline won't fail on an exit code unequal 0.
You can set the result of the pipeline by yourself (Source):
if(status != 0)
{
currentBuild.result = 'FAILURE'
}

Jenkins pipeline script with invoking powershell script file is not working in stages and gets hanged till i abort

Hi am working on creating a descriptive pipeline which has 4 simple stages. Each stage steps is to invoke a powershell file with arguments.
pipeline{
agent none
stages{
stage("demo1"){
steps{
powershell returnStatus: true, script: ".\\file1.ps1 ${p1} ${p2} ${p3} ${p4} ${p5}"
}
}
stage("demo2"){
steps{
powershell returnStatus: true, script: ".\\file2.ps1 ${p1} ${p2} ${p3}"
}
}
stage("demo3"){
steps{
powershell returnStatus: true, script: ".\\file3.ps1 ${p1} ${p2} ${p3}"
}
}
stage("demo4"){
steps{
powershell returnStatus: true, script: ".\\file4.ps1 ${p1} ${p2} ${p3}"
}
}
}
}
The pipeline starts successfully and completes 1st stage and moves to second stage. Once the second stage steps is completed, it is not further moving to the third step. In console output i am seeing a refresh symbol and the job status says in progress. Until i abort the job the still loading.
Please help me in resolving the issue and what is the resolution for this.
Hey Guys thanks for all your support in making this issue resolved. As #mkemmerz and #DibakarAditya mentioned, all process has to be completed to proceed further. In my case winniumdriver process is still on, thats the reason jenkins is not moving to next stage. Added a command to kill the process. Working perfectly

Raise Abort in Jenkins Job from Batch script

I have a Jenkins job, which do Git syncs and build the source code.
I added and created a "Post build task" option.
In 'post build task', I am searching for keyword "TIMEOUT:" in console output (this part is done) and want to declare job as Failed and Aborted if keyword matches.
How can I raise / declare the Job as Aborted from batch script if keyword matches. Something like echo ABORT?
It is easier if you want mark it as "FAIL"
Just exit 1 will do that.
It is tricky to achieve "Abort" from post build task plugin, it is much easier to use Groovy post build plugin.
The groovy post build provide rich functions to help you.
Such as match function:
def matcher = manager.getLogMatcher(".*Total time: (.*)\$")
if(matcher?.matches()) {
manager.addShortText(matcher.group(1), "grey", "white", "0px", "white")
}
Abort function:
def executor = build.executor ?: build.oneOffExecutor;
if (executor != null){
executor.interrupt(Result.ABORTED)
}
Br,
Tim
you can simply exit the flow and raise the error code that you want:
echo "Timeout detected!"
exit 1
Jenkins should detect the error and set-up the build as failed.
The error code must be between 1 and 255. You can chose whatever your want, just be aware that some code are reserved:
http://tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
You can also consider using the time-out plugin:
https://wiki.jenkins.io/display/JENKINS/Build-timeout+Plugin
And another option is to build a query to BUILD ID URL/stop. Which is exactly what is done when you manually abort a build.
echo "Timeout detected!"
curl yourjenkins/job_name/11/stop

How to make jenkins job unstable from a bash script?

In most of my jenkins jobs, I have bash script.
In some conditions, I want to make my build instable.
When I exit the script with the code 0, the build finish in SUCCESS (GREEN COLOR) and when I exit with another code the job is failed (RED COLOR).
Is there a way to make the jenkins job unstable (YELLOW COLOR) from a bash script ?
If you use the pipeline plugin and write your jobs in groovy pipline dsl, yes:
try {
sh "yourscript.sh"
} catch(Exception e) {
currentBuild.result = 'UNSTABLE'
}
Jenkins is designed to set an automatic fail when the exit code of your script is 1. There are plenty of ways of overriding this, but most involve Jenkins CLI or a plugin. Using the returnStatus flag for shell commands https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/, Jenkins will not automatically fail but instead, return the status code.
Here's the documentation:
returnStatus (optional)
Normally, a script which exits with a nonzero status code will cause the step to fail with an exception. If this option is checked, the return value of the step will instead be the status code. You may then compare it to zero, for example.
script{
def returnVal = sh(
returnStatus: true,
script: '''
**your script here**
'''
)
if(returnVal != 0) {
currentBuild.result = 'UNSTABLE'
}
}

Resources