How to Retrieve Keep Forever Builds from the API?

Article ID:218155017
1 minute readKnowledge base

Issue

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

Environment

  • CloudBees Jenkins Operations Center

  • CloudBees Jenkins Enterprise

  • Jenkins

Resolution

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
    }
}
return;

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:

https://jenkins:port/api/xml?depth=4&xpath=//job[not(ancestor::primaryView)andnot(ancestor::view)andnot(ancestor::node)]/build[keepLog=%22true%22]/url&wrapper=forever

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))")

https://jenkins:port/api/xml?depth=4&tree=jobs[name,builds[keepLog,url],jobs[name,builds[keepLog,url]]]

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")

https://jenkins:port/api/xml?depth=4&tree=jobs[name,builds[keepLog],jobs[name,builds[keepLog]]]&xpath=//build[keepLog=%22true%22]&wrapper=forever

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