|
| 1 | +# Jenkins Notes |
| 2 | +* Author: Pedric Kng |
| 3 | +* Updated: 05 Dec 2019 |
| 4 | +*** |
| 5 | + |
| 6 | +## Clean Up Old Builds |
| 7 | + |
| 8 | +You can update the configuration of all existing jobs on a Jenkins Master by running the following Groovy Script within Manage Jenkins -> Script Console which will apply a permanent build discard policy to your jobs that you can configure by passing the desired values to the listed parameters. |
| 9 | + |
| 10 | +```groovy |
| 11 | +// NOTES: |
| 12 | +// dryRun: to only list the jobs which would be changed |
| 13 | +// daysToKeep: If not -1, history is only kept up to this day. |
| 14 | +// numToKeep: If not -1, only this number of build logs are kept. |
| 15 | +// artifactDaysToKeep: If not -1 nor null, artifacts are only kept up to this day. |
| 16 | +// artifactNumToKeep: If not -1 nor null, only this number of builds have their artifacts kept. |
| 17 | +
|
| 18 | +import jenkins.model.Jenkins |
| 19 | +
|
| 20 | +def dryRun = true |
| 21 | +def daysToKeep = 30 |
| 22 | +def numToKeep = 10 |
| 23 | +def artifactDaysToKeep = -1 |
| 24 | +def artifactNumToKeep = -1 |
| 25 | +
|
| 26 | +
|
| 27 | +Jenkins.instanceOrNull.allItems(hudson.model.Job).each { job -> |
| 28 | + if (job.isBuildable() && job.supportsLogRotator() && job.getProperty(jenkins.model.BuildDiscarderProperty) == null) { |
| 29 | + println "Processing \"${job.fullDisplayName}\"" |
| 30 | + if (!"true".equals(dryRun)) { |
| 31 | + // adding a property implicitly saves so no explicit one |
| 32 | + try { |
| 33 | + job.setBuildDiscarder(new hudson.tasks.LogRotator ( daysToKeep, numToKeep, artifactDaysToKeep, artifactNumToKeep)) |
| 34 | + println "${job.fullName} is updated" |
| 35 | + } catch (Exception e) { |
| 36 | + // Some implementation like for example the hudson.matrix.MatrixConfiguration supports a LogRotator but not setting it |
| 37 | + println "[WARNING] Failed to update ${job.fullName} of type ${job.class} : ${e}" |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | +return; |
| 43 | +``` |
| 44 | + |
| 45 | +# References |
| 46 | +Best Strategy for Disk Space Management: Clean Up Old Builds [[1]] |
| 47 | + |
| 48 | +[1]:https://support.cloudbees.com/hc/en-us/articles/215549798-Best-Strategy-for-Disk-Space-Management-Clean-Up-Old-Builds "Best Strategy for Disk Space Management: Clean Up Old Builds" |
0 commit comments