Skip to content

Instantly share code, notes, and snippets.

@kevin-brotcke
Last active November 9, 2023 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevin-brotcke/8f65f07e7314ae811df242abc70b2ef2 to your computer and use it in GitHub Desktop.
Save kevin-brotcke/8f65f07e7314ae811df242abc70b2ef2 to your computer and use it in GitHub Desktop.
Combined branch build discarder for Jenkins multibranch pipelines
import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject
/**
* Maintains a build history limit across ALL branches in a pipeline, not just per branch.
*
* <p>This script could be tweaked to save last successful, discard artificats, exclude certain
* branches, include only a certain pipeline, etc. See <a
* href="https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/tasks/LogRotator.java">LogRotator.java</a>
* for more examples.
*
* <p>Usage: Run in the /script console for dry run. If you are happy with the output, uncomment
* delete() below to take effect.
*/
def NUM_BUILDS_TO_KEEP = 30
Jenkins.instance.getAllItems(WorkflowMultiBranchProject.class).each { workflow ->
def builds = []
workflow.items.each { branch ->
builds += branch.getBuilds()
}
builds = builds.sort{it.time}.reverse().subList(Math.min(builds.size(), NUM_BUILDS_TO_KEEP), builds.size())
if (builds.size() > 0) {
println "Found $builds.size builds to delete from $workflow.fullName workflow."
}
builds.each { build ->
if (build.isBuilding()) {
println "Skipping $build because it's building."
} else if (build.isKeepLog()) {
println "Skipping $build because it's marked as keep."
} else {
println "Deleting build $build"
// Uncomment below to actually delete!
// build.delete()
}
}
}
@alexanderLinear
Copy link

I like it.

@alexanderLinear
Copy link

two changes in line #6:

  • This script could be tweaked to save last successfull, discard artificats, exclude certain

  • This script could be tweaked to save last successful, discard artifacts, exclude certain

@kevin-brotcke
Copy link
Author

Thanks, fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment