Is there a way to set next Build Number manually on Jenkins - jenkins

After system restart where Jenkins is stored, one of the jobs is constantly failing it is trying to create bulid with number 1 but there is already 1400 past builds. Is there a way to change it so the build will be created with correct increment so in this case 1401.
Full stactrace from jenkins:
java.lang.IllegalStateException: [Directory]\builds\1 already existed; will
not overwite with [Build.Name] #1
at hudson.model.RunMap.put(RunMap.java:189)
at jenkins.model.lazy.LazyBuildMixIn.newBuild(LazyBuildMixIn.java:178)
at hudson.model.AbstractProject.newBuild(AbstractProject.java:1011)
at hudson.model.AbstractProject.createExecutable(AbstractProject.java:1210)
at hudson.model.AbstractProject.createExecutable(AbstractProject.java:144)
at hudson.model.Executor$1.call(Executor.java:328)
at hudson.model.Executor$1.call(Executor.java:310)
at hudson.model.Queue._withLock(Queue.java:1251)
at hudson.model.Queue.withLock(Queue.java:1189)
at hudson.model.Executor.run(Executor.java:310)

You can use a groovy script in $JENKINS_URL/script as follows:
item = Jenkins.instance.getItemByFullName("jobName")
item.updateNextBuildNumber(1401)

It looks like you can use the "Next Build Number" plugin to accomplish this: https://wiki.jenkins.io/display/JENKINS/Next+Build+Number+Plugin

There is a file you can edit: $JENKINS_HOME/jobs/../nextBuildNumber
$ cat /var/lib/jenkins/jobs/my-project/branches/develop/nextBuildNumber
42
You will need to reload configuration after changing it.

Related

Display the username who ran the build in Build History

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'])

Increment variable value in TFS build +1

I have a Microsoft Visual Studio Team Foundation Server (Version 15.117.26714.0) with predefined variable $(ProjectBuildNumber).
Is there any way to increment, during build process, value of variable with minor build number by +1?
$(ProjectBuildNumber) = 663
So, that on next build it will be:
$(ProjectBuildNumber) = 664
You can't reference variables in the build number of the Build Definition. But what you can do is override the build number in the build itself. You can either use a magic log command or use my VSTS Variables Task to set the Build.BuildNumber in the build itself. The Variables Task does expand variable references. You could probably just set the value to the current value to get it expanded.
To issue the log command yourself use a batch script, PowerShell or bash to output the following specific string to the console:
##vso[build.updatebuildnumber]build number
Update build number for current build. Example:
##vso[build.updatebuildnumber]my-new-build-number
Minimum agent version: 1.88
source: https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
An alternative option is to use the $(Rev) option:
Build.BuildNumber = 1.1.$(Rev:.r)
That will automatically increase the variable each time the build runs.
To update a variable in a Build Definition use yet another extension:
These things combined should be able to get what you want.
In the variable section,
set the value of ProjectBuildNumber to $[counter('', 663)].
This will queue build starting with 663 as ProjectBuildNumber and increments by 1 for the subsequent queue of builds.
Unfortunately counter function (Expressions) is not available in TFS 2018. In this old version the best solution for me is to use a PowerShell script as the first Task of the build. You can than have your parameter
$(ProjectBuildNumber)
as an input argument, and place this inline script:
$ProjectBuildNumber=$args[0]
$ProjectBuildNumber++
Write-Host "##vso[task.setvariable variable=ProjectBuildNumber;]$ProjectBuildNumber"
After this Task you can use your incremented ProjectBuildNumber variable in all subsequent Tasks.

Get all logs of the current Jenkins build with currentBuild.rawBuild.getLog

I want all my jenkins logs of my current build in groovy
env.logs = currentBuild.rawBuild.getLog(1000).join('\n')
This works, but the problem here is I have to specify the amount of lines.
When I use:
env.logs = currentBuild.rawBuild.getLog().join('\n')
env.logs is empty. What is the right command to get all the logs without specifying the amount of lines. Is this possible?
currentBuild.rawBuild.log seems to work but is deprecated?
You can use the getLog method with a max value getLog(Integer.MAX_VALUE)
This is working for me - it reads the actual log file instead of using the API:
logFileContent = new File("${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log").collect {it}

How to get build time stamp from Jenkins build variables?

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);
}

How to reset build number in jenkins?

I am using Jenkins and Gradle to build my java project.
Every time I build my project, I get a new build number on the Jenkins screen.
The following is my Jenkins build info:
Success > Console Output #96 03-Jan-2014 15:35:08
Success > Console Output #95 03-Jan-2014 15:27:29
Failed > Console Output #94 03-Jan-2014 15:26:16
Failed > Console Output #93 03-Jan-2014 15:25:01
Failed > Console Output #92 03-Jan-2014 15:23:50
Success > Console Output #91 03-Jan-2014 12:42:32
Success > Console Output #90 03-Jan-2014 12:02:45
I want to reset the Jenkins build number like:
Success > Console Output #1 03-Jan-2014 12:02:45
How can I reset the build number in Jenkins?
Can be easier done from groovy script console .
Go to http://your-jenkins-server/script
In script window enter:
item = Jenkins.instance.getItemByFullName("your-job-name-here")
//THIS WILL REMOVE ALL BUILD HISTORY
item.builds.each() { build ->
build.delete()
}
item.updateNextBuildNumber(1)
From here
Given your Hudson job is named FooBar,
rename FooBar to FooBar-Copy
create a new job named FooBar, using 'Copy existing job' option, from FooBar-Copy
delete FooBar-Copy
First wipeout workspace and get rid of previous builds.
On the server navigate to
the job dir eg. 'var/lib/jenkins/jobs/myJob' delete the
workspace & build dirs as well as any polling files, lastSuccessful,
lastStable files etc. You should only have config.xml and
lastBuildNumber.
Shut down jenkins using something like service jenkins stop
Edit the file called nextBuildNumber, inserting 1 instead of the current build number
Start up jenkins again, service jenkins start
Log into jenkins and go to your job and hit build. Should start building job#1
If you want set the next build number, there is plugin "NextBuildNumber" for that. But this will not work in your case because the build number you need, which is 1, is lesser than your current build number.
Here need to wipe out all the previous builds first. You can do this by running this simple script
Go to -> Manage Jenkins -> Script console
// change this variable to match the name of the job whose builds you want to delete
def jobName = "Your Job Name"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
Now you can set next build number to 1 and run the build. It will start with 1. :)
Its that simple.
Update - Jenkins now has a Purge Job History plugin to get this done in easiest way. Checkout the page for more details - https://wiki.jenkins.io/display/JENKINS/Purge+Job+History+Plugin
To more generally reset your build number to N (where N is not necessarily 1):
Delete any existing builds where buildNumber >= N.
Edit Program Files (x86)/Jenkins/jobs/yourjob/nextBuildNumber. Set the number it contains to N.
From Jenkins, select Manage Jenkins -> Reload Configuration from Disk.
Expanding on the accepted answer, here's how to do it for all projects at once:
Jenkins.instance.allItems.each() {
item -> item.builds.each() {
build -> build.delete()
}
item.updateNextBuildNumber(1)
}
As an extention of #antweiss's excellent answer, we can actually go further ...
There's no need to delete the full Build History, if you don't want to, you can simply roll back time, to a prior point:
resetNumberTarget = 14
item = Jenkins.instance.getItemByFullName("Project Name [from project Dashboard]")
//println(item)
item.builds.each() { build ->
//println(build)
//println(build.number)
if(build.number >= resetNumberTarget)
{
//println("About to Delete '" + build + "'")
build.delete()
}
}
item.updateNextBuildNumber(resetNumberTarget)
If you want a dummy run, to check what it's going to do, without actually doing it, simply comment out the build.delete() and item.updateNextBuildNumber(resetNumberTarget) lines and uncomment the various print commands.
Documentation:
Details of these objects were hard to find, but I identified the following:
item is a FreeStyleProject (or possibly, just any type of Abstract Project?)
build appears to be a Run, thus exposing a number property and inheritting a delete() method from Job
Use Purge Job History plugin (Jenkins >= 2.176.1)
https://plugins.jenkins.io/purge-job-history/
You can use either nexBuildNumber plug-in or simply modify nexBuildNumber file to reset build number.
Following are the steps that you need to perform:
Go to .jenkins/Jobs/<YourJobName>/build/, take backup of this folder(if you need for future use) and delete build folder.
Note: Once you clean up old builds, you lose build histories and they
are no longer available on the Jenkins dashboard.
Reload the configuration(Jenkins -> Manage Jenkins).
Set next build version to 1 by either using the Next Build Number plug-in or modifying the nextBuildNumber file in yourjob directory.
So I tried the above solution and getting the following error.,
groovy.lang.MissingPropertyException: No such property: builds for
class:
org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject.
So I tried this,
item = Jenkins.get().getItem("Job Name")
jobs = item.getAllJobs()
jobs.each() { item ->
builds = item.getBuilds()
builds.each() { b ->
b.delete()
}
item.updateNextBuildNumber(1)
}
and it worked!!
Here is variation of #antweiss answer for multi-branch pipeline
items = Jenkins.instance.getItemByFullName("your-job-name-here").getItems()
//THIS WILL REMOVE ALL BUILD HISTORY
items.collectMany { it.builds }.each { build ->
build.delete()
}
items.each {
it.updateNextBuildNumber(1)
}
To reset build numbers of all jobs:
Jenkins.instance.getAllItems(AbstractProject.class).each {
item = Jenkins.instance.getItemByFullName(it.fullName)
//THIS WILL REMOVE ALL BUILD HISTORY
item.builds.each() { build ->
build.delete()
}
item.updateNextBuildNumber(1)
}
I found an easy way to do this.
Wipe out your work space.
Go to each builds which saved on Jenkins and delete it.
Set build number to 1 then build.
Jenkins use previous build to determine the next build number, if build number you input is lower than previous build number, Jenkins will automatically increase your build number to higher than previous build. So here we just

Resources