How to use ${currentBuild.result} to indicate "SUCCESS" not "null" - jenkins

My Jenkins declarative pipeline has the following post action:
mail to: '<snip>',
subject: "Status of pipeline: ${currentBuild.fullDisplayName}",
body: "${env.BUILD_URL} has result ${currentBuild.result}"
When the build succeeds the content of the email body is:
<job name> has result null
I understand that the value of ${currentBuild.result}" is null when the job succeeds, but this isn't convenient for the user. What is the recommended way of printing "SUCCESS" (or "FAILURE" etc) in the body message?

Use ${currentBuild.currentResult} instead.
currentResult
typically SUCCESS, UNSTABLE, or FAILURE. Will never be null.
The syntax of the available global variables is available at ${YOUR_JENKINS_URL}/pipeline-syntax/globals. See more info about globals in Jenkins documentation.
Also see https://issues.jenkins.io/browse/WEBSITE-364

You can add mail step inside post step in pipeline as below :
pipeline {
agent any
stages {
stage('Example Test') {
steps {
echo 'Hello, JDK'
}
}
}
post {
success {
echo "${env.BUILD_URL} has result success"
}
failure {
echo "${env.BUILD_URL} has result fail"
}
}
}

CurrentBuild contains the following property. You can use them according to your need.
_class,
actions,
artifacts,
building,
description,
displayName,
duration,
estimatedDuration,
executor,
fullDisplayName,
id,
keepLog,
number,
queueId,
result,
timestamp,
URL,
changeSets,
culprits,
nextBuild,
previousBuild,
number

Related

Jenkins job to catch a particular error message from downstream job and retrigger it

I am trying to retrigger a downstream job if the job fails during the first build with the error "invalid JWT token", I want this job to retrigger again with changed parameters.
I am able to retrigger it with different parameters as of now, but what I want to achieve here is want the job to retrigger only if I get the error as " invalid Jwt token" only.
can someone help me with this, I am trying to make use of try-catch block
this is the pipeline job as of now
I assume you decide on the error by looking at the log of the second Job. If that's the case have a look at the following. Here I'm using propagate: false
pipeline {
agent any
stages {
stage('Job') {
steps {
script {
def jobBuild = build(job: 'SecondJob', wait: true, propagate: false)
def result = jobBuild.getResult()
if(result == "FAILURE"){
def log = jobBuild.getRawBuild().getLog()
if(log.contains("invalid JWT token")){
echo "Rerunning the JOB!!!!"
} else {
error "Downstream Job failed due to other error."
}
}
}
}
}
}
}

Unable to access environment variable in email body

Here's one environment variable MODEL in my Jenkins declarative script. But I am not able to use this MODEL variable into the email body. Though it is working fine in the email subject!
pipeline {
agent any
stages {
stage(‘Test’) {
environment {
MODEL = “Some ML Model v1.2.3”
}
steps {
...
}
post {
always {
emailext attachLog: true,
attachmentsPattern: ‘**/reports/*.html’,
mimeType: “text/html”,
to: 'myemail#company.com’,
subject: “Test - ${env.MODEL} Build [${env.BUILD_NUMBER}]“,
body: '''<html>
<p><b>Regression Test Report</b></p>
<p>$MODEL</p>
<p>${MODEL}</p>
<p>"${MODEL}"</p>
<p>"${env.MODEL}"</p>
<p>""'${MODEL}'""</p>
<p>""'${env.MODEL}'""</p>
<p>"""${env.MODEL}"""</p>
<p>${ENV,var="MODEL"}</p>
<p>"${ENV,var="MODEL"}"</p>
<p>Build URL: $BUILD_URL</p>
<p>Build Status: $BUILD_STATUS</p>
<br />
<p><b>Console Output</b></p>
<pre>${BUILD_LOG_REGEX, regex="^.*test session starts.*$", showTruncatedLines=false}</pre>
<pre>${BUILD_LOG_EXCERPT, start="^.*test.*==$", end="^.*in.*==$"}</pre>
...
</html>'''
}
}
}
}
}
I have tried multiple things as shown, but this script is just producing following email body:
Also went through several links like the following but still did not get the drill. Please suggest something.
Jenkins: Passing user defined variables to Email-Ext plugin
For such cases you need to use triple double quotes when defining template:
body:"""
var: ${var}
envvar: ${env.VAR}
"""
I tryed '''+VAR+''' and it's work fine!

GitHub Webhook not triggering the Jenkins Pipeline

I want to trigger a pipeline when Pull Request is Merged..ie "action": "closed","merged":"true"
Webhook got 200 response for Jenkins
pipeline.groovy:
pipelineJob(job_name) {
parameters {
stringParam('APP_URL', app_url, 'URL of the Application')
stringParam('APP_MERGE_STATUS', app_merge_status, 'Merge Status to Trigger Job')
booleanParam('MERGED', true, 'Flag to Trigger the job')
stringParam('APP_ARTIFACT_BUCKET', artifact_bucket, 'Bucket url to upload artifacts')
stringParam('payload')
}
triggers {
genericTrigger {
genericVariables {
genericVariable {
key("APP_MERGE_STATUS")
value("\$.action")
expressionType("JSONPath")
}
genericVariable {
key("MERGED")
value("\$pull_request.merged")
expressionType("JSONPath")
}
}
printPostContent(true)
regexpFilterText("\$action")
regexpFilterExpression("")
}
}
Generic Variables I have mentioned are also used to trigger the job without github..[using parameters]
I am not sure how to write the generic trigger variables and regex for the trigger
Scenario: PR is closed and merged
If your Jenkins is exposed to the internet, you can subscribe to the webhook in Github itself
or use jenkins declarative pipeline to make use of
Got the solution..I missed to add "generic-webhook-trigger" in payload url

Office365ConnectorSend pipeline step does not work

I'm trying to configure Jenkinks notifications to MS Teams. I followed the instructions by setting up and configuring Jenkins app on the relevant channel and Office365 plugin in Jenkins. I get standard job status notifications if I request them.
Now I need to be able to send custom notifications from the pipeline. I was expecting that using office365ConnectorSend pipeline step would do just that:
office365ConnectorSend message:'Test message', webhoolUrl:'office365ConnectorSend message: 'Manual test', webhookUrl: 'https://outlook.office.com/webhook/.../JenkinsCI/...'
When the pipeline runs, everything is reported as working correctly and the job completes successfully, yet the message never appears in teams.
How can post a message?
office365ConnectorSend message:'Test message', webhoolUrl:'office365ConnectorSend message: 'Manual test', webhookUrl: 'https://outlook.office.com/webhook/.../JenkinsCI/...'
Did you check the spelling? it should be webhookUrl not webhoolUrl and only once.
I use something like this in the post pipeline action step, where MSTEAMS_HOOK is defined as an environment variable within the environment {} pipeline directive to the Teams URL.
success {
office365ConnectorSend (
status: "Pipeline Status",
webhookUrl: "${MSTEAMS_HOOK}",
color: '00ff00',
message: "Test Successful: ${JOB_NAME} - ${BUILD_DISPLAY_NAME}<br>Pipeline duration: ${currentBuild.durationString}"
)
}
Try to replace the single quote to double in the webhookUrl.
webhookUrl:"$msteams_url"
Except for the spell error, the script you have been trying works fine. The problem might be with your network restriction. The HTTP request triggered by jenkins might have been blocked. Try pasting the webhook URL in the browser of the system you are using and check the response. If the response says something other than 'Invalid webhook request - GET not supported'. There is a possibility the request has been a failure.
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
office365ConnectorSend message: 'Manual test', webhookUrl: 'https://outlook.office.com/webhook/*'
}
}
}
}

How do I know which stage of jenkins pipeline has failed

In my Jenkins pipelines I generally use post declarative function to send me an email incase the pipeline has failed.
A simple syntax of the post function is as under:
post {
failure {
mail to: 'team#example.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
}
In the above email, I also want to mention which stage (lets say the pipeline has 5 to 6 stages) of the pipeline has failed. How can I do that? Any help is much appreciated.
An extension to the above requirement will be to provide the user with the actual error log (of the stage that has failed) also as a part of the failure notification email.
Idea is, when a user receives a failure notification from jenkins, he should know which stage of the pipeline has failed along with the error log.
Thanks in advance.
There is a variable called env.STAGE_NAME which you can use. However, in your case you will probably need to store the stage name in a different variable, because when you get the env.STAGE_NAME in a post stage the result will be Declarative: Post Actions. Instead, you will need to store the stage name in a variable in all stages. So once a stage fails - Jenkins will not continue with the next stages and therefore you will have the "failed" stage name.
Here's an example:
def FAILED_STAGE
pipeline {
agent { label "master" }
stages {
stage("Stage 1") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 1"
}
}
}
stage("Stage 2") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 2"
error "failed for some reason."
}
}
}
stage("Stage 3") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 3"
}
}
}
}
post {
failure {
echo "Failed stage name: ${FAILED_STAGE}"
}
}
}
There might be a better way to do it, but I haven't found it so far.
Regarding the logs - As of JENKINS-40526 you could possibly use the API and get the log file from there, but I am not sure you can get the parameters you need from within the pipeline. The other solution would be to use emailext and email the entire build log file:
emailext attachLog: true, body: '', compressLog: true, subject: 'Build failed.', to: 'somebody#somewhere.com'

Resources