I want to run the script for two products product1 and product2 , the command contains string product1 product2 and runs script for two products as expected. The command looks like below on console:
pytest -v -s --browser_name "MobileChrome" --env "Production" --product_name product1 product2 --disable-pytest-warnings
But the problem is the result file names are product1.xlsx and product2.xlsx respectively, but as I've passed ${product_Name}.xlsx in email attachment, Jenkins is trying to attach product1 product2.xlsx which doesn't exist. somehow I want to split the product name in attachment section and make it product1.xlsx and product2.xlsx so that I will get both files correctly attached in email.
in above image product name will become product1 product2 after passing below values in build with parameters:
$product_Name is a string parameter and can hold multiple values:
Prior to sending mails you could try:
Project config → Post-build Actions → Add post-build action ▼: Groovy Postbuild → Groovy Script (not tested in real):
def myProducts = build.getEnvironment(listener).get('Product_Name')
// From Editable Email Notification → Attachments' inline help: 'The format is a comma separated list of Ant include file syntax.'
env.filesToBeAttached = ... // create a string "referenceData/product1.xlsx,referenceData/product2.xlsx" from myProducts here
// use it in Editable Email Notification → Attachments: $filesToBeAttached
Hopefully the environment for the following Editable Email Notification is adapted accordingly. I'm not 100 % sure about that.
A trivial alternative would be to enter at build parameter Product_Name: referenceData/product1.xlsx,referenceData/product2.xlsx.
See also:
Access to build environment variables from a groovy script in a Jenkins build step (Windows)
Is it possible to set environment variables on a groovy function
Related
I would like to send the full name of the previous build that was received by using the following:
Run previousBuild = steps.currentBuild.rawBuild.getPreviousBuildInProgress()
in order to send to getItemByFullName as you can see below,
Jenkins.instance.getItemByFullName(previousBuildPath)
I tried to find it in the Run class hudson Documentation with no success.
while printing previousBuild I got the name with the build number like:
previousBuild- > project_neme/build_name #100
But I want to get only the name with no String substring cutting.
You are looking for display name property. Display name is the name given to each build (if you update it during execution) followed by a build number. The display name will only return the build name.
Jenkins.instance.getItemByFullName('JobName').getLastBuild().displayName
Read here
https://javadoc.jenkins.io/hudson/model/Job.html
How can I display the username who executed the build next to the build number? like in the image below
Try entering Started by ([\S]+) in the section "Post-build Actions ->
Set build description -> Regular expression" of your job config.
You can add user name to build description.
currentBuild.description = currentBuild.getBuildCauses().shortDescription[0]
Then you will get something like bellow
* #1 Feb 24, 2020 10:00 AM
| Started by user max
If you want use user only then
currentBuild.description = currentBuild.getBuildCauses().userId[0]
Data structure is :
[{"_class":"hudson.model.Cause$UserIdCause","shortDescription":"Started by user max","userId":"max","userName":"max"}]
See, install and enable for the job
https://plugins.jenkins.io/build-user-vars-plugin/
Then change name of build using BUILD_USER_ID variable, like
#${BUILD_NUMBER}: ${GIT_REVISION,length=8} (${GIT_BRANCH}) by ${BUILD_USER_ID}
Add Groovy Postbuild and user build vars plugin
edit job configure,check 【Set jenkins user build variables】,then you can get env variables 'BUILD_USER'
Post-build Actions, add 【Groovy Postbuild】, Groovy Script change to
manager.addShortText(manager.envVars['BUILD_USER'])
I have a Pylint running in a Jenkins pipeline. To implement it, I used Gerrit trigger plugin and Next Generation Warnings plugin. Everything is working as expected - Jenkins is joining the review, checks change with pylint and generates report.
Now, I'd like to post pylint score in a custom "Build successful" message. I wanted to pass the pylint score to a environment variable and use it in dedicated window for Gerrit plugin message.
Unfortunately no matter what I try, I cannot pass any "new" variable to the message. Passing parameters embedded in pipeline works (e.g. patchset number).
I created new environment variable in Configure Jenkins menu, tried exporting to shell, writing to it (via $VAR and env. syntax) but nothing works - that is, build message displays raw string like $VAR instead of what variable contains.
What should I do to pass local pylint score (distinct for every pipeline occurence) to the custom build message for Gerrit?
I don't think the custom message can be used for this. This is just supposed to be a static message.
They way I do this is to use the SSH command to perform the review. You can also achieve the same using the REST API.
First I run my linting and white space checking script that will generate a json file with the information I would like to pass to Gerrit. Next I send it to Gerrit using SSH. See below my pipeline script and an example json file.
As a bonus I have added the robot comments. This will now show up in your review as a remark from Jenkins that line 8 of my Jenkins file has a trailing white space. You can easily replace this with your lint result of you like or just ignore it and only put the message. It is easier to use a json file as it will make it easier to create multi line messages
node('master') {
sh """
cat lint_change.json | ssh -p ${env.GERRIT_PORT} ${env.GERRIT_HOST} gerrit review ${env.GERRIT_PATCHSET_REVISION} --json
"""
}
Example json file:
{
"labels": {
"Code-Style": "-1"
},
"message": "Lint Bot Review\nLint Results:\n Errors: 0\n Warnings: 0\n\nWhitespace results:\n Errors: 1",
"robot_comments": {
"Jenkinsfile": [
{
"robot_id": "lint-bot",
"line": "8",
"message": "trailing whitespace."
}
]
}
}
Alternatively, you may want to look at a new gerrit-code-review-plugin that should make this things even easier. However, I have not tried this yet.
I have a jenkins job that builds an iOS app and runs a test script which posts the results into an xml file using xcpretty.
In the post build actions I publish the results in xml format. Is it possible to get some of the contents of these results and put them into the email notification to send i.e.
Tests Passed: {Number of passed tests}
Tests Failed: {Number of failed tests}
Total Tests: {Total tests}
In your "Execute Shell"
echo "test log" > /some/file/path/logFile.txt
Then in your "Editable Email Notification-Default Content"
${FILE,path="/some/file/path/logFile.txt"}
You can use attach the XML file to the e-mail and try to use HTML block and add the file name inside. I used it for jpeg file and it worked great.
It's also possible to use a script to examine the file and assign an environment variable, that you'd later use in the content of the email.
How can I get build time stamp of the latest build from Jenkins?
I want to insert this value in the Email subject in post build actions.
Build Timestamp Plugin will be the Best Answer to get the TIMESTAMPS in the Build process.
Follow the below Simple steps to get the "BUILD_TIMESTAMP" variable enabled.
STEP 1:
Manage Jenkins -> Plugin Manager -> Installed...
Search for "Build Timestamp Plugin".
Install with or without Restart.
STEP 2:
Manage Jenkins -> Configure System.
Search for 'Build Timestamp' section, then Enable the CHECKBOX.
Select the TIMEZONE, TIME format you want to setup with..Save the Page.
USAGE:
When Configuring the Build with ANT or MAVEN,
Please declare a Global variable as,
E.G. btime=${BUILD_TIMESTAMP}
(use this in your Properties box in ANT or MAVEN Build Section)
use 'btime' in your Code to any String Variables etc..
NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration
You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html.
Replace https://<your-jenkins>/ with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html).
One of the environment variables is :
BUILD_ID
The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)
If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"} in the subject line of your email.
One way this can be done is using shell script in global environment section, here, I am using UNIX timestamp but you can use any shell script syntax compatible time format:
pipeline {
agent any
environment {
def BUILDVERSION = sh(script: "echo `date +%s`", returnStdout: true).trim()
}
stages {
stage("Awesome Stage") {
steps {
echo "Current build version :: $BUILDVERSION"
}
}
}
}
Try use Build Timestamp Plugin and use BUILD_TIMESTAMP variable.
Generate environment variables from script (Unix script) :
echo "BUILD_DATE=$(date +%F-%T)"
I know its late replying to this question, but I have recently found a better solution to this problem without installing any plugin. We can create a formatted version number and can then use the variable created to display the build date/time.
Steps to create: Build Environment --> Create a formatted version number:
Environment Variable Name: BUILD_DATE
Version Number Format String: ${BUILD_DATE_FORMATTED}
thats it. Just use the variable created above in the email subject line as ${ENV, var="BUILD_DATE"} and you will get the date/time of the current build.
You can use the Jenkins object to fetch the start time directly
Jenkins.getInstance().getItemByFullName(<your_job_name>).getBuildByNumber(<your_build_number>).getTime()
also answered it here:
https://stackoverflow.com/a/63074829/1968948
BUILD_ID used to provide this information but they changed it to provide the Build Number since Jenkins 1.597. Refer this for more information.
You can achieve this using the Build Time Stamp plugin as pointed out in the other answers.
However, if you are not allowed or not willing to use a plugin, follow the below method:
def BUILD_TIMESTAMP = null
withCredentials([usernamePassword(credentialsId: 'JenkinsCredentials', passwordVariable: 'JENKINS_PASSWORD', usernameVariable: 'JENKINS_USERNAME')]) {
sh(script: "curl https://${JENKINS_USERNAME}:${JENKINS_PASSWORD}#<JENKINS_URL>/job/<JOB_NAME>/lastBuild/buildTimestamp", returnStdout: true).trim();
}
println BUILD_TIMESTAMP
This might seem a bit of overkill but manages to get the job done.
The credentials for accessing your Jenkins should be added and the id needs to be passed in the withCredentials statement, in place of 'JenkinsCredentials'. Feel free to omit that step if your Jenkins doesn't use authentication.
This answer below shows another method using "regexp feature of the Description Setter Plugin" which solved my problem as I could not install new plugins on Jenkins due to permission issues:
Use build timestamp in setting build description Jenkins
If you want add a timestamp to every request from browser to jenkins server.
You can refer to the jenkins crumb issuer mechanism, and you can hack the /scripts/hudson-behavior.js add modify here. so it will transform a timestamp to server.
/**
* Puts a hidden input field to the form so that the form submission will have the crumb value
*/
appendToForm : function(form) {
// add here. ..... you code
if(this.fieldName==null) return; // noop
var div = document.createElement("div");
div.innerHTML = "<input type=hidden name='"+this.fieldName+"' value='"+this.value+"'>";
form.appendChild(div);
}