Automatically Marking Jenkins builds as keep forever


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


  • CloudBees Jenkins Enterprise
  • Jenkins


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

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.*


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())
// 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:

Have more questions? Submit a request


  • 0
    Marlene Cote

    I have tried to get this code to work by fixing things like missing quotes and parenthesis, but I am having no luck.  Is someone available to help me with this?  I am learning groovy script, so I am probably making a novice mistake, but it would be nice for you to at least post working code if you are offering it.

    I believe this line is missing a quote and parenthesis.

    def envVarsMap = build.parent.builds[0].properties.get("envVarsonfig.putAll(envVarsMap)
    Edited by Marlene Cote
Please sign in to leave a comment.