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

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.

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"
build.keepLog(true)

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
myBuild.keepLog(true)

Have more questions?

4 Comments

  • 0
    Avatar
    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
  • 0
    Avatar
    Dheeraj Reddy

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

  • 0
    Avatar
    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
    Avatar
    Dheeraj Reddy

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

Please sign in to leave a comment.