Skip to content

Instantly share code, notes, and snippets.

@hemp
Created January 29, 2020 15:40
Show Gist options
  • Save hemp/8bfe46a7b8b42b8ffbc1c20dc887dad4 to your computer and use it in GitHub Desktop.
Save hemp/8bfe46a7b8b42b8ffbc1c20dc887dad4 to your computer and use it in GitHub Desktop.
Groovy to set the scan interval for Jenkins multibranch pipeline jobs

Scan Multibranch Pipeline Trigger

Enabling this schedule on all multi-branch pipeline build jobs helps with maintaining consistency between the code repository and Jenkins.

There is not a way to set this through a Jenkinsfile nor run this from inside a build job (reference).

The help documentation for this trigger provides better scenario details.

def jobs = jenkins.model.Jenkins.instance.items
.findAll { it instanceof org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject }

println "Adding PeriodicFolderTrigger to ${jobs.size()} jobs"

def addedCount = 0;
def updatedCount = 0;

jobs
.each { job ->
    def isEmpty = job.getTriggers().isEmpty()
    if (isEmpty) {
        addedCount++
    } else {
        updatedCount++;
    }
    println job.getIndexing().getTimestamp().format("yyyy-MM-dd'T'HH:mm'Z'") + " - ${isEmpty ? 'ADDED' : 'UPDATED'} - ${job.name}"
    // https://github.com/jenkinsci/cloudbees-folder-plugin/blob/master/src/main/java/com/cloudbees/hudson/plugins/folder/computed/PeriodicFolderTrigger.java#L259
    // addTrigger will replace if it exists
    job.addTrigger(new com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger("7d"));
}
println "Added PeriodicFolderTrigger for ${addedCount} jobs"
println "Updated PeriodicFolderTrigger for ${updatedCount} jobs"
null
@jglick
Copy link

jglick commented Feb 25, 2022

jenkins.model.Jenkins.instance.items will only find top-level multibranch projects. To search also in folders you would need to use .allItems. You do not need Groovy-level filtering, either; try https://javadoc.jenkins.io/hudson/model/ItemGroup.html#getAllItems-java.lang.Class-

def jobs = jenkins.model.Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject)

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