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



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

There are different ways to do it automatically based on the type of the Project.

In the case of Pipeline, the property is exposed on the Build object. Therefore, you can, for example, keep the current build forever by adding the following in your Pipeline:

currentBuild.keepLog = true

To do this in other types of projects, you can leverage the Groovy plugin’s build step “Execute system Groovy script” to execute the “keepLog” function on the build that has to be kept forever.

For example, to mark the current build:

println "Marking current build as Keep Forever"

To mark any arbitrary project’s build:

// Get the Project/Job object
def job = jenkins.model.Jenkins.instance.getItemByFullName("folder/test-discard-old-builds", Job.class)
// Get the build by number
def myBuild = job.getBuild("4")
// Keep this build forever

Have more questions?


  • 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
  • 1
    Dheeraj Reddy

    Curious if there is a way to automatically unmark jenkins builds that are marked as "Keep this build forever" ?

  • 0
    Denys Digtiar

    Marlene: You are right about the missing syntax. Let us review the article.

    Pendridheeraj: `keepLog` method accepts a `boolean`. If you want to unmark a build pass it `false` instead or `true`.

  • 0
    Dheeraj Reddy

    @Denys Digtiar: That makes sense..! Thanks a lot for the quick response :)

  • 1
    Yingkit Yingkit

    @Denys Digtiar: Pipeline documentation says that keepLog is not writable for any builds but currentBuild, is there another way to modify that field for older builds in Pipeline? For example, is it possible to do the “Execute system Groovy script” method in a Jenkinsfile?

  • 0
    Max Cascone

    @Yingkit Yingkit: use a script block in your declarative step to execute non-declarative syntax. 

    Also, I am curious if you ever found a way to un-set an older build as keepForever.

    stage {
    steps {
    script {
    // non-declarative stuff here
    Edited by Max Cascone
Please sign in to leave a comment.