111

The groovy syntax generator is NOT working for sample step properties: Set Job Properties. I've selected Discard old builds and then entered 10 in the Max # of builds to keep field and then Generate Groovy and nothing shows up.

Jenkins version: 2.7

StephenKing
  • 36,187
  • 11
  • 83
  • 112
tarabyte
  • 17,837
  • 15
  • 76
  • 117

11 Answers11

243

As for declarative syntax, you can use the options block:

pipeline {
  options {
    buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '30'))
  }
  ...
}

Parameters for logRotator (from the source code):

  • daysToKeepStr: history is only kept up to this days.
  • numToKeepStr: only this number of build logs are kept.
  • artifactDaysToKeepStr: artifacts are only kept up to this days.
  • artifactNumToKeepStr: only this number of builds have their artifacts kept.

More information can be found in Cloudbees knowledge base and in the docs for options block.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 5
    Is this supposed to be per branch or per pipeline? It does not seem to work in my environment. – nroose Jun 07 '19 at 22:36
  • Is it general practice to need to refer to source code to get the parameters for various options? The docs only references `numToKeepStr` and luckily I found your response here to find the other params. Kind of a mess how they document things. Thanks though you're a life saver. – emmdee Sep 01 '20 at 16:57
  • 1
    Can someone show the context for putting this buildDiscarder options statement inside a (multi-pipeline) stage block? I've tried but my build fails. – Christopher Sep 03 '20 at 18:54
  • 4
    When you discard a "build", does it discard both the build artifacts and the associated repository? – dangerousdave Jan 19 '21 at 17:39
  • 4
    @vadim-kotov Your answer is a class act on how to provide a great answer. You give all of the pertinent details plus the external reference where to read them. If everyone on stackoverflow spent the time you spend in answering this question everyone would greatly benefit. Kudos. – mario May 14 '21 at 16:46
  • 2
    @vadim-kotov, I have tried and it does not work with a pipeline. Tried to keep both properties and just 1 properties, no luck. Any clues? – Varun Verma Oct 26 '21 at 22:10
57

You can use the properties method which, nested within the BuildDiscarderProperty eventually has the key you want to set. I still don't have a solid way to look up the correct syntax of each key. After much guessing and checking:

properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10']]]);

Note that this snippet is for scripted syntax.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
tarabyte
  • 17,837
  • 15
  • 76
  • 117
  • 1
    This works but why is this nested inside two maps and how did you work this out? – Rupert Madden-Abbott Feb 14 '18 at 13:15
  • I'm looking at your answer, and I don't understand what it does. Does it keep the last 10 builds or last 10 days? Can I keep last 10 weeks or 3 months' builds? Please explain the meaning of each `*Str` field in `strategy`. Teach a man to fish...etc – Abhijit Sarkar Mar 02 '18 at 18:43
  • 1
    @AbhijitSarkar all of the options are described in the javadoc of that class: https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/tasks/LogRotator.java#L53 – apottere Apr 02 '18 at 18:17
  • @apottere 1. The link isn't in the answer. 2. If I were to look into Javadoc, there's no need for an answer. The answer should be complete as much as possible. External links are ok, as long as the relevant portion is copy-pasted and explained here. – Abhijit Sarkar Apr 02 '18 at 19:55
  • 2
    @AbhijitSarkar I'm not the OP, I was just letting you know where you could find the answer. – apottere Apr 03 '18 at 15:44
27

For Scripted Pipelines use:

properties([
    buildDiscarder(logRotator(daysToKeepStr: '3', numToKeepStr: '3')),
])
StasKolodyuk
  • 4,256
  • 2
  • 32
  • 41
22

Jenkins has built-in syntax generator pages.

Pipeline-Syntax: Snippet Generator
<your jenkins url>/pipeline-syntax/

Pipeline-Syntax: Directive Generator
<your jenkins url>/directive-generator/

Discard old builds example from Directive Generator discard old builds example

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
Chad Gilman
  • 231
  • 2
  • 6
10
  1. To Discard build after particular number of days:

     options {
         buildDiscarder(logRotator(daysToKeepStr: '7'))
     }
    
  2. To Discard build after particular number of builds:

     options {
         buildDiscarder(logRotator(numToKeepStr: '7'))
     }
    
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jerald Sabu M
  • 1,200
  • 3
  • 16
  • 19
10

For declarative pipeline you can add this:

options {

    buildDiscarder(
        logRotator(
            // number of build logs to keep
            numToKeepStr:'5',
            // history to keep in days
            daysToKeepStr: '15',
            // artifacts are kept for days
            artifactDaysToKeepStr: '15',
            // number of builds have their artifacts kept
            artifactNumToKeepStr: '5'
        )
    )
}
bhordupur
  • 872
  • 13
  • 14
  • 1
    Thx, but where did you find the info? Codes? – silencej Jul 15 '20 at 03:07
  • 1
    I normally do it from here `jenkins-base-url:port if any/pipeline-syntax/`. Here is also another https://javadoc.jenkins.io/hudson/tasks/LogRotator.html. I also look into sometimes github source code of the plugin to understand in details. @silencej – bhordupur Jul 19 '20 at 19:59
6

Vadim's answer did not work for me for some unknown reason. I simplified it down as follows and it works now:

options {
    buildDiscarder(logRotator(numToKeepStr: '3'))
}
Firdaus
  • 61
  • 1
  • 3
3

If you're using the Jenkins Job DSL to create a job or pipelineJob, you can use any of the following formats to add the discard builds configuration to your job:

Option 1

This option modifies the XML structure of the job directly.

pipelineJob {
  configure {
    it / 'properties' / 'jenkins.model.BuildDiscarderProperty' {
      strategy {
        'daysToKeep'('7')
        'numToKeep'('10')
        'artifactDaysToKeep'('-1')
        'artifactNumToKeep'('-1')
      }
    }
  }
}

Option 2

pipelineJob {
  logRotator(7, 10, -1, -1)
}

Option 3

pipelineJob {
  logRotator {
    numToKeep(10)
    daysToKeep(7)
    artifactNumToKeep(-1)
    artifactDaysToKeep(-1)
  }
}

See the following links for additional details:

blacktide
  • 10,654
  • 8
  • 33
  • 53
2

If you want to configure the build retention on the multibranch pipeline job level (vs in all the individual Jenkinsfiles) this is possible too: https://issues.jenkins-ci.org/browse/JENKINS-30519?focusedCommentId=325601&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325601

In addition to the BuildRetentionBranchProperty you can configure any other of the *BranchPropertys in here: https://github.com/jenkinsci/branch-api-plugin/tree/master/src/main/java/jenkins/branch

They might not be shown in the GUI though, at least for me with Jenkins 2.73.2. But you can still use JobDSL or modify the config.xml directly (I didn't say that ;-))

Torben Knerr
  • 784
  • 6
  • 15
  • Are you talking about [Job DSL Plugin](https://wiki.jenkins.io/display/JENKINS/Job+DSL+Plugin)? It is not the same thing as Jenkins Pipelines. I mean, not everybody who use Pipelines are using Job DSL Plugin. – Vadim Kotov Feb 05 '18 at 13:45
  • @VadimKotov no, not really. I had the problem of configuring the build retention in Jenkins Pipelines. I did not want to do that in the Jenkinsfile, but on job level instead. I used Job DSL here, but it does not really matter as this is only a means for automating the setup of build jobs. However, it seems that there is bug in the GUI which prevents the above settings to appear when you configure the build job manually. (JobDSL does nothing you couldn't do via the GUI otherwise) – Torben Knerr Feb 06 '18 at 22:54
2

If you need a programmatic way (i.e. doing this from a function, rather than using options{} pipeline syntax):

def someFunction() {
  ...
  properties([
    buildDiscarder(logRotator(numToKeepStr: '5'))
  ])
}
David Lavender
  • 8,021
  • 3
  • 35
  • 55
1

The following worked for me using Jenkins Configuration as Code (JCasC):

jobs: |
    jobs:
      - script: >
            folder('Jobs')
      - script: >
          pipelineJob('Jobs/banana') {
            logRotator(10,5,10,5)
            definition {
              cpsScmFlowDefinition {
                scm {
                  gitSCM {
                    doGenerateSubmoduleConfigurations(false)
                    browser {}
                    gitTool(null)
                    userRemoteConfigs {
                        userRemoteConfig {
                          credentialsId("banana")
                          url('git@myrepo.git')
                          refspec(null)
                          name(null)
                        }
                        branches {
                          branchSpec {
                            name('remotes/origin/mybranch/update')
                          }
                        }
                     }
                  }
                }
                scriptPath('somefolder/Jenkinsfile')
                lightweight(true)
              }
            }
          }
Banoona
  • 1,470
  • 3
  • 18
  • 32