Automatically Marking Jenkins builds as keep forever

Issue

  • Builds which are promoted to stable environments (e.g. Production) are automatically purged according to the configured Jenkins old build purge schedule

Environment

  • CloudBees Jenkins Enterprise
  • Jenkins

Resolution

To manually prevent a build from getting purged according to the schedule, click on the ‘Keep this build forever’ button to lock the build.

To automatically do this, we need to create a separate job which uses a groovy script. First, install the Groovy Plugin. Next create a new job, add a build step “Execute system Groovy script” which utilizes the “keepLog” function and retrieves the number of your build job…using this example:

def job = jenkins.model.Jenkins.instance.getItem("test-discard-old-builds")
def myBuild = job.getBuild("4")
boolean keeper = true
myBuild.keepLog(true)

Alternatively, this can be done in sequence by creating a job “Keep Build Forever” and running it in sequence - to mark the build after it’s been promoted (e.g. to “Test” or “Production” environment). To use this method, create a build job named “Keep Build Forever” that contains the following code in the “Execute system Groovy script” step:

// Beginning of groovy script
import hudson.model.*

BUILD_JOB_NAME = "Build"

def getBuildVariable(String key) {
 def config = new HashMap()
 def thr = Thread.currentThread()
 def build = thr?.executable
 def buildMap = build.getBuildVariables()
 def envVarsMap = build.parent.builds[0].properties.get("envVarsonfig.putAll(envVarsMap)
 return config.get(key)
}

def getJobs() {
 def hi = hudson.model.Hudson.instance
 return hi.getItems(hudson.model.Job)
}

def getBuildJob() {
 def buildJob = null
 def jobs = getJobs()
 (jobs).each { job ->
 if (job.displayName == BUILD_JOB_NAME) {
 buildJob = job
 }
 }
 return buildJob
}

def getBuildRunToMark(hudson.model.Job job) {
 def runToMark = null
 (job.getBuilds()).each { run ->
 if (String.valueOf(run.number) == getBuildVariable("BUILD_NUMBER")) {
 runToMark = run
 }
 }
 return runToMark
}

def runToMark = getBuildRunToMark(getBuildJob())
runToMark.keepLog(true)
// End of groovy script

To automatically mark the build, use the “Parameterized Trigger Plugin” at the end of the “Test” or “Production” environment deployment job to trigger the “Keep Build Forever” job on success.

More context including an illustrated use case can be found in this article: https://themettlemonkey.wordpress.com/2013/01/31/automatically-marking-a-jenkins-builds-as-keep-forever/

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.