I am using Promoted Build plugin. And using some custom groovy scripts to validate the build! I wanted to access the value of BUILD_NUMBER from the groovy script. Can anyone suggest me how i can achieve this?
Another thing i am writing println statement in this groovy script but its no where getting logged. Any suggestion to debug the script flow how can i log the info ?
Thanks
If it's in runtime you can use:
def env = System.getenv()
//Print all the environment variables.
env.each{
println it
}
// You can also access the specific variable, say 'username', as show below
String user= env['USERNAME']
if it's in system groovy you can use:
// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable
//Get from Env
def stashServer= build.parent.builds[0].properties.get("envVars").find {key, value -> key == 'ANY_ENVIRONMENT_PARAMETER' }
//Get from Job Params
def jobParam= "jobParamName"
def resolver = build.buildVariableResolver
def jobParamValue= resolver.resolve(jobParam)
Any println is sending output to the standard output steam, try looking at the console log.
Good luck!
Related
Does Jenkins provide a variable when replay is ran? If so what is that? I see in the log that is writes Replayed but I am not looking to scrape the console output.
You can use 'cause' of which has triggered the job, in rawBuild.
def replayClassName = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause"
def isReplay = currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replayClassName) }
*refered from
How to know inside jenkinsfile / script that current build is a replay?
I am using jenkins pipeline 2.0, and I would like to get another job's latest successful build number.
What's the pipeline syntax to use?
You can get it this way
def buildNumber = Jenkins.instance.getItem('jobName').lastSuccessfulBuild.number
If you get a RejectedAccessException you will have to approve those methods, see In-process Script Approval
To add to Vitalii's answer, this is in case you're using Multibranch Pipeline Plugin:
def buildNumber = Jenkins.instance.getItem('jobName').getItem('branchName').lastSuccessfulBuild.number
It's so annoying to get approvals in enterprise environment(a lot of request and approvals)
So I am using following API way to get the latest build number.
import groovy.json.JsonSlurperClassic
httpRequest url: 'https://jenkinsurl.local/job/Build/api/json', outputFile: 'output.json'
def jsonFile = readFile(file: 'output.json')
def data = new JsonSlurperClassic().parseText(jsonFile)
latestBuildNumber = "${data.lastSuccessfulBuild.number}"
def build_job = build job: "Build"
build_job_number = build_job.getNumber()
We are in the early phases of using Jenkins DSL. One challenge we have come across is being able to read in an existing jobs plugin settings so that we retain it before running the DSL. This allows us the ability to give the Jenkins users the option to keep some of their settings. We have successfully retained the schedule settings for our jobs but the newest challenge is being able to retain a plugin setting. Specifically a setting in the "ExtendedEmailPublisher" plugin. We would like to retain the value:
In the config.xml file for this job in the ExtendedEmailPublisher tags we see the following:
<publishers>
<hudson.plugins.emailext.ExtendedEmailPublisher>
<recipientList>Our_Team#Our_Team.com</recipientList>
<configuredTriggers>
<hudson.plugins.emailext.plugins.trigger.FailureTrigger>
<email>
<recipientList/>
<subject>$PROJECT_DEFAULT_SUBJECT</subject>
<body>$PROJECT_DEFAULT_CONTENT</body>
<recipientProviders>
<hudson.plugins.emailext.plugins.recipients.ListRecipientProvider/>
</recipientProviders>
<attachmentsPattern/>
<attachBuildLog>false</attachBuildLog>
<compressBuildLog>false</compressBuildLog>
<replyTo>$PROJECT_DEFAULT_REPLYTO</replyTo>
<contentType>project</contentType>
</email>
</hudson.plugins.emailext.plugins.trigger.FailureTrigger>
</configuredTriggers>
<contentType>default</contentType>
<defaultSubject>$DEFAULT_SUBJECT</defaultSubject>
<defaultContent>$DEFAULT_CONTENT</defaultContent>
<attachmentsPattern/>
<presendScript>$DEFAULT_PRESEND_SCRIPT</presendScript>
<classpath/>
<attachBuildLog>false</attachBuildLog>
<compressBuildLog>false</compressBuildLog>
<replyTo>$DEFAULT_REPLYTO</replyTo>
<saveOutput>false</saveOutput>
<disabled>false</disabled>
</hudson.plugins.emailext.ExtendedEmailPublisher>
</publishers>
The value we would like to extract/preserve from this XML is:
<disabled>false</disabled>
We have tried getting the existing values using groovy but cant seem to find the right code. Our first idea was to try to read the value from the config.xml using the XmlSlurper. We ran this from the Jenkins Script Console:
def projectXml = new XmlSlurper().parseText("curl http://Server_Name:8100/job/Job_Name/api/xml".execute().text);
*we use 8100 for our Jenkins port
Unfortunately while this does return some config info it does not return plugin info.
Then, we also tried running the following to read/replace the existing settings:
def oldJob = hudson.model.Hudson.instance.getItem("Job_Name")
def isDisabled = false // Default Value
for(publisher in oldJob.publishersList) {
if (publisher instanceof hudson.plugins.emailext.ExtendedEmailPublisher) {
isDisabled = publisher.disabled
}
}
And while this works if executed from the Jenkins Script Console, when we try to use it in a DSL Job we get the message:
Processing provided DSL script
ERROR: startup failed:
script: 25: unable to resolve class
hudson.plugins.emailext.ExtendedEmailPublisher
# line 25, column 37.
if (publisher instanceof hudson.plugins.emailext.ExtendedEmailPublisher)
{
1 error
Finished: FAILURE
SOLUTION UPDATE:
Using url #aflat's URL suggestion for getting the raw XML config info, I was able to use the XML Slurper and then use the getProperty method to assign the property I wanted to a variable.
def projectXml = new XmlSlurper().parseText("curl http://Server_Name:8100/job/Job_Name/config.xml".execute().text);
def emailDisabled = projectXml.publishers."hudson.plugins.emailext.ExtendedEmailPublisher".getProperty("disabled");
If you want to parse the config.xml, use
def projectXml = new XmlSlurper().parseText("curl http://Server_Name:8100/job/Job_Name/config.xml");
That should return your raw config.xml data
Under "Manage Jenkins->Configure Global Security" did you try disabling "Enable script security for Job DSL scripts"?
I have Job_1, and Job_2.
In Job_1,
Step 1: Execute system Groovy script
import hudson.model.*
def build = Thread.currentThread().executable
def param = []
param.add(new StringParameterValue('ARTS', "safsaf"))
def pa = new ParametersAction (param)
build.addAction(pa)
Step 2: Trigger/call builds on other projects
Projects to build: JOB_2
Add parameters: Current build parameters
Step 3:
Execute Windows batch command
echo arts = %ARTS%
In Job_2,
Step 1:
Execute Windows batch command
echo arts from Job_1 = %ARTS%
Build Job_1, it does print out:
arts = safsaf
build_2 was successfully triggered, and print out:
arts from Job_1 = (blank)
it appears that only parameters in Job_1 defined in the This build is parameterized section can be passed to the downstream projects.
is this the expected behavior? How can parameters added in the fly be passed along?
I tried and this works:
in Job_1,
define a string parameter "ARTS" in the This build is parameterized section,
and change Groovy script from
import hudson.model.*
def build = Thread.currentThread().executable
def param = []
param.add(new StringParameterValue('ARTS', "safsaf"))
def pa = new ParametersAction (param)
build.addAction(pa)
to
import hudson.model.*
def build = Thread.currentThread().executable
build.replaceAction(
new ParametersAction(
new StringParameterValue('ARTS', 'safsaf')))
to overwrite the value of "ARTS", instead of adding a new parameter.
Give Parameterized Trigger Plugin a try. My downstream job was kicked off by a post build step Trigger parameterized build on other projects with Current build parameter from the plugin instead of the regular downstream job. Anything defined in This build is parameterized in Job_2 would pick up parameters passed from Job_1.
I may not be using this absolutely correct and I think there is a limitation on what can be captured vs cannot, but so far this captures all desired parameter from Job_1 for me.
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);
}