After upgrade Jenkins, the email cannot show environment variable when build failure - jenkins

Upgrade the Jenkins to 2.278, after upgrade, if build
error, the content of email show:
$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:
Check console output at $BUILD_URL to view the results.
It will not display the real value, but I can find them
in the 'Environment variables ', like:
BUILD_CAUSE MANUALTRIGGER
BUILD_CAUSE_MANUALTRIGGER true
BUILD_DISPLAY_NAME #35
BUILD_ID 35
BUILD_NUMBER 35
BUILD_TAG jenkins-trigger-test-35
BUILD_URL http://192.168.10.99:8080/job/trigger-test/35/
...
then I upgrade the Email Extension Plugin to 2.80, but
still with no lucky.
Does anyone know what's wrong?
Thanks a lot.

The solution is to update Token Macro to 2.14 or later

Related

Jenkins with two cucumber reports override each other

I've got Jenkins job with 2 stages generating two separate reports (they use https://plugins.jenkins.io/cucumber-reports/ this plugin and HTML publisher), Jenkins itself is on GKE (so after the job is done and files are generated on the agent they are transferred to master); The issue I've got it that first HTML Report and Cucumber reports are generated properly but when the second stage is run, it overrides some of the files from the first step, resulting in 403 error from Jenkins when checking the report. Any thoughts on how to deal with it?
Access to Jenkins was denied you don't have the authorisation to view this page.
HTTP ERROR 403
Please use ,
reportTitle: 'name'
entry in cucumber step , it wont override your report .
Example:
step([$class: 'CucumberReportPublisher',
failedFeaturesNumber: xxx,
failedScenariosNumber: xxx,
failedStepsNumber: xxxx,
fileExcludePattern: '',
fileIncludePattern: '**/*.json',
jsonReportDirectory: xxx,
parallelTesting: false,
reportTitle: xxx ,
pendingStepsNumber: xx,
skippedStepsNumber: xx,
trendsLimit: 0,
undefinedStepsNumber: xx
])
Jenkins version : Jenkins 2.230
Cucumber reports plugin : 5.2.0

Jenkins: "${env.SVN_REVISION}" variable returns null

I would like to read the revision number from Jenkins job when the job fails
Revision number:
Job script:
failure {
echo 'JENKINS PIPELINE FAILED'
notifyBitbucket
commitSha1: "${env.SVN_REVISION}",
considerUnstableAsSuccess: false,
credentialsId: 'UFCBitbucket',
disableInprogressNotification: true,
ignoreUnverifiedSSLPeer: true,
includeBuildNumberInKey: false,
prependParentProjectKey: false,
projectKey: '',
stashServerBaseUrl: 'https://bitbucket.url.local:8080'
}
I have trouble with Jenkins environment variable - "${env.SVN_REVISION}". This variable returns null value.
I can not solve this problem. Please help to solve this problem
Thanks in advance
I don't think the env-variable SVN_REVISION does even exist.
All available Git-plugin env-variables can be seen here (and the Jenkins' ones here).
I would suggest you use the following environment-variable to get the revision:
GIT_COMMIT - SHA1 of the commit used in this build
On the other hand you can get the revision also by executing the git command directly per sh / bash:
git rev-parse HEAD

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

Can't access $BUILD_LOG in Jenkins pipeline

How do I access $BUILD_LOG in a Jenkins pipeline, or is there a better way of getting the log output?
Going off of this answer, I've been trying to access the $BUILD_LOG environment variable, but when I try
echo "${BUILD_LOG, maxLines=50, escapeHtml=false}"
the build errors out:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 11: unexpected token: BUILD_LOG # line 11, column 29.
echo "${BUILD_LOG, maxLines=50, escapeHtml=false}"
And if I try
echo "$BUILD_LOG"
I get this error:
groovy.lang.MissingPropertyException: No such property: BUILD_LOG for class: groovy.lang.Binding
What am I doing wrong? Or is this the wrong way to access the printed output?
I had the same problem with declarative pipelines and a step like:
emailext(
subject: "foo",
to: "bar",
body: """<p>FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Console output (last 250 lines):<hr><pre>${BUILD_LOG}</pre></p>"""
I had email ext plugin installed.
The solution was to escape the $-sign of the the macro that should be expanded by the plugin, like so:
...
<p>Console output (last 250 lines):<hr><pre>\${BUILD_LOG}</pre></p>"""
...
And be sure to use double quotes.
This way groovy (?) will first expand all the environment variables, and leaves the escaped variables to be dealt with by email ext plugin.
Still haven't found a solution to use BUILD_LOG parameter in a pipeline job with emailext plugin.
As a small solace, I found a workaround to access build log in another way:
currentBuild.rawBuild.getLog(15)
Where 15 is a number of last log lines I want to show.
The example is:
emailext attachLog: true,
body: "Build failed" +
"<br> See attached log or URL:<br>${env.BUILD_URL}" +
"<br><br> <b>The end of build log is:</b> <br>" +
currentBuild.rawBuild.getLog(15).join("<br>"),
mimeType: 'text/html',
subject: "Build failed",
to: 'myemail#somedomain.com'
Note that you have to approve a few script signatures at the In-Process Script Approval in order to allow usage of this function.
From the answer you linked the BUILD_LOG variable is set by the email-extension plugin. Do you have this configured correctly as this may be your issue.

Getting the build status in post-build script

I would like to have a post-build hook or similar, so that I can have the same output as e. g. the IRC plugin, but give that to a script.
I was able to get all the info, except for the actual build status. This just doesn't work, neither as a "Post-build script", "Post-build task", "Parameterized Trigger" aso.
It is possible with some very ugly workarounds, but I wanted to ask, in case someone has a nicer option ... short of writing my own plugin.
It works as mentioned with the Groovy Post-Build Plugin, yet without any extra quoting within the string that gets executed. So I had to put the actual functionality into a shell script, that does a call to curl, which in turn needs quoting for the POST parameters aso.
def result = manager.build.result
def build_number = manager.build.number
def env = manager.build.getEnvironment(manager.listener)
def build_url = env['BUILD_URL']
def build_branch = env['SVN_BRANCH']
def short_branch = ( build_branch =~ /branches\//).replaceFirst("")
def host = env['NODE_NAME']
def svn_rev = env['SVN_REVISION']
def job_name = manager.build.project.getName()
"/usr/local/bin/skypeStagingNotify.sh Deployed ${short_branch} on ${host} - ${result} - ${build_url}".execute()
Use Groovy script in post-build step via Groovy Post-Build plugin. You can then access Jenkins internals via Jenkins Java API. The plugin provides the script with variable manager that can be used to access important parts of the API (see Usage section in the plugin documentation).
For example, here's how you can execute a simple external Python script on Windows and output its result (as well as the build result) to build console:
def command = """cmd /c python -c "for i in range(1,5): print i" """
manager.listener.logger.println command.execute().text
def result = manager.build.result
manager.listener.logger.println "And the result is: ${result}"
For this I really like the Conditional Build Step plugin. It's very flexible, and you can choose which actions to take based on build failure or success. For instance, here's a case where I use conditional build step to send a notification on build failure:
You can also use conditional build step to set an environment variable or write to a log file that you use in subsequent "execute shell" steps. So for instance, you might create a build with three steps: one step to compile code/run tests, another to set a STATUS="failed" environment variable, and then a third step which sends an email like The build finished with a status: ${STATUS}
Really easy solution, maybe not to elegant, but it works!
1: Catch all the build result you want to catch (in this case SUCCESS).
2: Inject an env variable valued with the job status
3: Do the Same for any kind of other status (in this case I catch from abort to unstable)
4: After you'll be able to use the value for whatever you wanna do.. in this case I'm passing it to an ANT script! (Or you can directly load it from ANT as Environment variable...)
Hope it can help!
Groovy script solution:-
Here I am using groovy script plugin to take the build status and setting it to the environmental variable, so the environmental variable can be used in post-build scripts using post-build task plugin.
Groovy script:-
import hudson.EnvVars
import hudson.model.Environment
def build = Thread.currentThread().executable
def result = manager.build.result.toString()
def vars = [BUILD_STATUS: result]
build.environments.add(0, Environment.create(new EnvVars(vars)))
Postscript:-
echo BUILD_STATUS="${BUILD_STATUS}"
Try Post Build Task plugin...
It lets you specify conditions based on the log output...
Basic solution (please don't laugh)
#!/bin/bash
STATUS='Not set'
if [ ! -z $UPSTREAM_BUILD_DIR ];then
ISFAIL=$(ls -l /var/lib/jenkins/jobs/$UPSTREAM_BUILD_DIR/builds | grep "lastFailedBuild\|lastUnsuccessfulBuild" | grep $UPSTREAM_BUILD_NR)
ISSUCCESS=$(ls -l /var/lib/jenkins/jobs/$UPSTREAM_BUILD_DIR/builds | grep "lastSuccessfulBuild\|lastStableBuild" | grep $UPSTREAM_BUILD_NR)
if [ ! -z "$ISFAIL" ];then
echo $ISFAIL
STATUS='FAIL'
elif [ ! -z "$ISSUCCESS" ]
then
STATUS='SUCCESS'
fi
fi
echo $STATUS
where
$UPSTREAM_BUILD_DIR=$JOB_NAME
$UPSTREAM_BUILD_NR=$BUILD_NUMBER
passed from upstream build
Of course "/var/lib/jenkins/jobs/" depends of your jenkins installation

Resources