How to Retrieve Keep Forever Builds from the API?

Article ID:218155017
1 minute readKnowledge base


Using REST api, how to get a list of Keep Forever builds?


  • CloudBees Jenkins Operations Center

  • CloudBees Jenkins Enterprise

  • Jenkins


1) Using a Groovy Script

The easiest way is to use a Groovy script like the following:

import hudson.model.Job
import jenkins.model.Jenkins
import hudson.model.Run

* Get all builds with "Keep Forever" property.
Jenkins.instance.getAllItems().findAll { item -> (item instanceof Job) && !(((Job)item).builds.isEmpty()) }.each {
    it.builds.findAll { build -> build.isKeepLog()}
    .each {
        println it.getAbsoluteUrl()
        //Do something for this build

2) Using the REST API

The problem with this REST API is that:

  1. you need to specify the depth

  2. The deeper the more demanding

Following is a REST API to retrieve the "Keep Forever" builds URL using the XML API:


To overcome the demanding aspect, you can use the techniques discussed in the article Taming the Jenkins JSON api with depth and "tree". Following shows how to retrieve all jobs' name and the corresponding builds' URL and keepLog option: (jobs[name,builds[keepLog,url] = "I want jobs. For each job I want the name of the job and its builds. For each build I want the URL and the keepLog option") (jobs[name,builds[keepLog,url],jobs[name,builds[keepLog,url]]] = "I want the same as above including nested jobs (inside folder(s))")


Using XPATH you can parse the information you need. (//build[keepLog=%22true%22]" = "I want all builds of that tree for which keepLog is true")


You can test these commands in your browser and use the parameter &pretty=true to display a "readable" tree.