list items

get name and classes

Jenkins.instance.getAllItems( Job.class ).each {
  println it.name + " -> " + it.fullName + ' ~> ' + it.class
}
  • result
    marslo - class org.jenkinsci.plugins.workflow.job.WorkflowJob
    fs - class hudson.model.FreeStyleProject
    

list all jobs and folders

jenkins.model.Jenkins.instance.getAllItems( AbstractItem.class ).each {
  println(it.fullName)
}
  • result:
    marslo/marslo
    marslo/fs
    

list all WorkflowJob

import org.jenkinsci.plugins.workflow.job.WorkflowJob

jenkins.model.Jenkins.instance.getAllItems( WorkflowJob.class ).each {
   println it.fullName
}

list all AbstractProject

Abstract Project: freestyle, maven, etc...

Jenkins.instance.getAllItems( AbstractProject.class ).each {
  println it.fullName
}

list all folders

import com.cloudbees.hudson.plugins.folder.Folder

Jenkins.instance.getAllItems( Folder.class ).each {
  println it.fullName + ' ~> ' + it.getClass()
}

list all disabled projects/jobs

jenkins.model.Jenkins.instance
       .getAllItems( Job.class )
       .findAll { it.disabled }
       .collect { it.fullName }
  • or

    jenkins.model.Jenkins.instance
           .getAllItems(jenkins.model.ParameterizedJobMixIn.ParameterizedJob.class)
           .findAll{ it.disabled }
           .each { println it.fullName }
    
  • or

    jenkins.model.Jenkins.instance
           .getAllItems(jenkins.model.ParameterizedJobMixIn.ParameterizedJob.class)
           .findAll{ it.disabled }
           .collect { it.fullName }
    

list inactive jobs

[!NOTE] List jobs haven't been built in 6 months

final long CURRENT_TIME  = System.currentTimeMillis()
final long BENCH_MARK    = 6*30*24*60*60

Jenkins.instance.getAllItems( Job.class ).collect { project ->
  project.getLastBuild()
}.findAll { build ->
  build && ( CURRENT_TIME - build.startTimeInMillis ) / 1000 > BENCH_MARK
}

list cron jobs

[!NOTE|label:references:]

list all cron jobs

import hudson.triggers.TimerTrigger

jenkins.model.Jenkins j      = jenkins.model.Jenkins.instance
hudson.model.Descriptor cron = j.getDescriptor( TimerTrigger )

println j.getAllItems(Job).findAll { Job job ->
  job?.triggers?.get(cron)
}.collectEntries { Job job ->
    [ (job.fullName):  job.triggers.get(cron).spec ]
}.collect {
  "${it.key.padRight(30)}: ${it.value}"
}.join('\n')

disable timer trigger in freestyle only

import hudson.model.*
import hudson.triggers.*

TriggerDescriptor TIMER_TRIGGER_DESCRIPTOR = Hudson.instance.getDescriptorOrDie( TimerTrigger.class )
Jenkins.instance.getAllItems(Job).findAll { item ->
  item.getTriggers().get( TIMER_TRIGGER_DESCRIPTOR )
}.each { item ->
  if ( item instanceof hudson.model.FreeStyleProject ) {
    item.removeTrigger(TIMER_TRIGGER_DESCRIPTOR)
    println(item.fullName + " Build periodically disabled");
  } else {
    println(item.fullName + " Build periodically remains enabled; not as Freestyle project");
  }
}

"DONE"
  • or

    import hudson.model.*
    import hudson.triggers.*
    
    TriggerDescriptor TIMER_TRIGGER_DESCRIPTOR = Hudson.instance.getDescriptorOrDie( TimerTrigger.class )
    
    for( item in Jenkins.instance.getAllItems(Job) ) {
      def timertrigger = item.getTriggers().get( TIMER_TRIGGER_DESCRIPTOR )
      if ( timertrigger ) {
        if (item.class.canonicalName == "hudson.model.FreeStyleProject") {
          item.removeTrigger(TIMER_TRIGGER_DESCRIPTOR)
          println(item.name + " Build periodically disabled");
        }
        else {
          println(item.name + " Build periodically remains enabled; not as Freestyle project");
        }
      }
    }
    
  • example 2:

    Jenkins.instance.getAllItems(Job).each {
      def jobBuilds=it.getBuilds()
    
      // Check the last build only
      jobBuilds[0].each { build ->
        def runningSince  = groovy.time.TimeCategory.minus( new Date(), build.getTime() )
        def currentStatus = build.buildStatusSummary.message
        def cause = build.getCauses()[0] //we keep the cause
    
        //triggered by a user
        def user = cause instanceof Cause.UserIdCause? cause.getUserId():null;
    
        if( !user ) {
          println "[AUTOMATION] ${build}"
        } else {
          println "[${user}] ${build}"
        }
      }
    }
    return
    

get pipeline definitions

[!TIP|label:references:]

get pipeline scm definition

[!TIP]

import org.jenkinsci.plugins.workflow.job.WorkflowJob

jenkins.model.Jenkins.instance.getAllItems( WorkflowJob.class ).findAll{
  it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
}.each {
  println it.fullName.toString().padRight(30) +
          ( it.definition?.scm?.branches?.join() ?: '' ).padRight(20) +
          ( it?.definition?.scriptPath ?: '' ).padRight(30) +
          it.definition?.scm?.userRemoteConfigs.collect { it.credentialsId }.join().padRight(30) +
          it.definition?.scm?.repositories?.collect{ it.getURIs() }?.flatten()?.join()
}

"DONE"

-- result --
marslo/sandbox/sandbox        */main              jenkinsfile/sandbox           GIT_SSH_CREDENTIAL            git://github.com:marslo/pipelines
marslo/sandbox/dump           */dev               jenkinsfile/dump              GIT_SSH_CREDENTIAL            git://github.com:marslo/pipelines
...

get pipeline scriptPath

[!TIP]

import org.jenkinsci.plugins.workflow.job.WorkflowJob

Jenkins.instance.getAllItems(WorkflowJob.class).findAll{
  it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
}.each {
  println it.fullName.toString().padRight(30) + ' ~> ' + it?.definition?.getScriptPath()
}

"DONE"

-- result --
marslo/sandbox/sandbox         ~> jenkins/jenkinsfile/sandbox.Jenkinsfile
marlso/sandbox/dump            ~> jenkins/jenkinsfile/dump.Jenkinsfile
...

get typical scm

[!NOTE]

jenkins.model.Jenkins.instance.getAllItems( hudson.model.Job.class ).findAll {
  it.hasProperty( 'typicalSCM' ) &&
  it.typicalSCM instanceof hudson.plugins.git.GitSCM
}.each { job ->
  println job.fullName.padRight(40) + ' : ' +
          ( job.typicalSCM.branches?.join() ?: '' ).padRight(40) +
          job.typicalSCM.userRemoteConfigs?.collect { it.credentialsId }.join().padRight(30) +
          job.typicalSCM.repositories?.collect{ it.getURIs() }?.flatten()?.join()
}

"DONE"

get pipeline scm branch

import org.jenkinsci.plugins.workflow.job.WorkflowJob

String branch = 'develop'

jenkins.model.Jenkins.instance.getAllItems(WorkflowJob.class).findAll{
  it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
}.findAll {
  ! ( it.definition?.scm instanceof hudson.scm.NullSCM ) &&
  ! it.definition?.scm?.branches?.any{ it.getName().contains(branch) }
}.each {
  println it.fullName.toString().padRight(50) + ' : ' +
          it.definition?.scm?.branches?.collect{ it.getName() }?.join(', ')
}

"DONE"

-- result --
$ ssh jenkins.domain.com groovy =< scmBranchPath.groovy
marslo/sandbox/sandbox                             : refs/heads/sandbox/marslo
marslo/sandbox/dump                                : refs/heads/utility

get all SCMs

[!NOTE]

  • get all SCM definitions via getSCMs, including
    • Libraries
    • last builds, including all stages calls GitSCM
  • getSCMs
    • getLastSuccessfulBuild ?: getLastCompletedBuild ?: definedSCMs
Jenkins.instance.getAllItems( Job.class ).findAll {
  it.SCMs &&
  it.SCMs.any { scm -> scm instanceof hudson.plugins.git.GitSCM }
}.each { job ->
  println job.fullName.padRight(50) + ':'
  job.SCMs.branches.eachWithIndex { scm, idx ->
    println '\t - ' + job.SCMs.branches[idx].join().padRight(45) +
                      job.SCMs.userRemoteConfigs[idx].credentialsId.join().padRight(30) +
                      job.SCMs.repositories[idx].collect { it.getURIs() }.flatten().join()
  }
}

"DONE"
  • or without lastBuild

    Jenkins.instance.getAllItems( Job.class ).findAll {
      it.hasProperty( 'typicalSCM' ) &&
      it.typicalSCM instanceof hudson.plugins.git.GitSCM
    }.each { job ->
      println job.fullName.padRight(40) + ' : ' +
              ( job.typicalSCM.branches?.join() ?: '' ).padRight(40) +
              job.typicalSCM.userRemoteConfigs?.collect { it.credentialsId }.join().padRight(30) +
              job.typicalSCM.repositories?.collect{ it.getURIs() }?.flatten()?.join()
    }
    
    "DONE"
    
    -- result --
    marslo/whitebox/whitebox                          : main             ED25519_SSH_CREDENTIAL     git://github.com:marslo/pipelines
    marslo/sandbox/dump                               : sandbox/dump     ED25519_SSH_CREDENTIAL     git://github.com:marslo/pipelines
    
  • or

    Jenkins.instance.getAllItems( Job.class ).findAll {
      it.hasProperty( 'typicalSCM' ) &&
      it.typicalSCM instanceof hudson.plugins.git.GitSCM
    }.each { job ->
      println job.fullName.padRight(50) + ':' +
              '\n\t - ' + job.typicalSCM.branches.join() +
              '\n\t - ' + job.typicalSCM.userRemoteConfigs.collect { it.credentialsId }.join() +
              '\n\t - ' + job.typicalSCM.repositories?.collect{ it.getURIs() }?.flatten()?.join()
    }
    
    "DONE"
    
    -- result --
    marslo/whitebox/whitebox                          :
       - main
       - ED25519_SSH_CREDENTIAL
       - git://github.com:marslo/pipelines
    marslo/sandbox/dump                               :
       - sandbox/dump
       - ED25519_SSH_CREDENTIAL
       - git://github.com:marslo/pipelines
    

check pipeline isn't get from particular branch

[!TIP]

import org.jenkinsci.plugins.workflow.job.WorkflowJob

String branch = 'develop'

Jenkins.instance.getAllItems(WorkflowJob.class).findAll{
  it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition &&
  ! ( it.definition.scm instanceof hudson.scm.NullSCM )
}.findAll {
  ! it.definition?.scm?.branches?.any{ it.getName().contains(branch) }
}.each {
  println it.fullName.toString().padRight(50) + ' : ' +
          it.definition?.scm?.branches?.collect{ it.getName() }?.join(', ')
}

"DONE"

get pipeline bare script

[!TIP]

import org.jenkinsci.plugins.workflow.job.WorkflowJob

Jenkins.instance.getAllItems(WorkflowJob.class).findAll{
  it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition
}.each {
  println it.fullName.toString().padRight(30) + ' ~> ' + it?.definition?.getScript()
}

"DONE"

get particular job status

def job = Jenkins.instance.getItemByFullName('<group>/<name>')
println """
  Last success : ${job.getLastSuccessfulBuild()}
    All builds : ${job.getBuilds().collect{ it.getNumber() }}
    Last build : ${job.getLastBuild()}
   Is building : ${job.isBuilding()}
"""

list properties

[!NOTE] Java Code Examples for jenkins.model.Jenkins#getItemByFullName()

def job = Jenkins.instance.getItemByFullName('<group>/<name>')
println """
       job.getClass() : ${job.getClass()}
    job.isBuildable() : ${job.isBuildable()}
  job.getFirstBuild() : ${job.getFirstBuild()}
         job.getACL() : ${job.getACL()}
  "======================="
      job.getBuilds() : ${job.getBuilds()}
"""

get logRotator

import org.jenkinsci.plugins.workflow.job.WorkflowJob
import hudson.tasks.LogRotator

String JOB_PATTERN = 'pattern'

Jenkins.instance.getAllItems(WorkflowJob.class).findAll{
  it.fullName.startsWith( JOB_PATTERN ) && it.buildDiscarder
}.each { job ->
  LogRotator discarder = job.buildDiscarder
  println job.fullName.toString().padRight(30) + ' : ' +
          "builds=(${discarder.daysToKeep} days, ${discarder.numToKeep} total) " +
          "artifacts=(${discarder.artifactDaysToKeep} days, ${discarder.artifactNumToKeep} total)"
}

"DONE"

show logRotator via pattern

List<String> projects = [ 'project' ]

Jenkins.instance.getAllItems(Job.class).findAll {
  projects.any { p -> it.fullName.startsWith(p) }
}.each {
  println """
    >> ${it.fullName} :

            artifactDaysToKeep : ${it.logRotator?.artifactDaysToKeep    ?: '' }
         artifactDaysToKeepStr : ${it.logRotator?.artifactDaysToKeepStr ?: '' }
             artifactNumToKeep : ${it.logRotator?.artifactNumToKeep     ?: '' }
          artifactNumToKeepStr : ${it.logRotator?.artifactNumToKeepStr  ?: '' }
                    daysToKeep : ${it.logRotator?.daysToKeep            ?: '' }
                 daysToKeepStr : ${it.logRotator?.daysToKeepStr         ?: '' }
                     numToKeep : ${it.logRotator?.numToKeep             ?: '' }
                  numToKeepStr : ${it.logRotator?.numToKeepStr          ?: '' }

    --------------------------------------------------------------------------------

       getArtifactDaysToKeep() : ${it.logRotator?.getArtifactDaysToKeep()    ?: '' }
    getArtifactDaysToKeepStr() : ${it.logRotator?.getArtifactDaysToKeepStr() ?: '' }
        getArtifactNumToKeep() : ${it.logRotator?.getArtifactNumToKeep()     ?: '' }
     getArtifactNumToKeepStr() : ${it.logRotator?.getArtifactNumToKeepStr()  ?: '' }
               getDaysToKeep() : ${it.logRotator?.getDaysToKeep()            ?: '' }
            getDaysToKeepStr() : ${it.logRotator?.getDaysToKeepStr()         ?: '' }
                getNumToKeep() : ${it.logRotator?.getNumToKeep()             ?: '' }
             getNumToKeepStr() : ${it.logRotator?.getNumToKeepStr()          ?: '' }

  """
}

set logrotator

[!NOTE|label:references:]

update pipeline definition

[!NOTE]

update SCM definition

[!NOTE]

without output

#!/usr/bin/env groovy

import hudson.plugins.git.GitSCM
import hudson.plugins.git.UserRemoteConfig
import org.jenkinsci.plugins.workflow.job.WorkflowJob
import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
import com.cloudbees.plugins.credentials.common.StandardCredentials
import com.cloudbees.plugins.credentials.CredentialsProvider

String newCredId = 'ED25519_SSH_CREDENTIAL'

if ( CredentialsProvider.lookupCredentials( StandardCredentials.class, jenkins.model.Jenkins.instance)
                        .any { newCredId == it.id }
) {

  jenkins.model.Jenkins.instance.getAllItems( WorkflowJob.class ).findAll {
    it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition &&
    ! it.definition?.scm?.userRemoteConfigs.collect { it.credentialsId }.contains( newCredId )
  }.each { job ->

    GitSCM orgScm          = job.definition?.scm
    Boolean orgLightweight = job.definition?.lightweight

    List<UserRemoteConfig> newUserRemoteConfigs = orgScm.userRemoteConfigs.collect {
      newUrl = 'ssh://' + it.url.split('ssh://').last().split('@').last()
      new UserRemoteConfig( newUrl, it.name, it.refspec, newCredId )
    }
    GitSCM newScm = new GitSCM( newUserRemoteConfigs, orgScm.branches, orgScm.doGenerateSubmoduleConfigurations,
                                orgScm.submoduleCfg, orgScm.browser, orgScm.gitTool, orgScm.extensions
                              )
    CpsScmFlowDefinition flowDefinition = new CpsScmFlowDefinition( newScm, job.definition.scriptPath )

    job.definition = flowDefinition
    job.definition.lightweight = orgLightweight
    job.save()

    println ">> " + job.fullName + " DONE !"
  }

} else {
  println "${newCredId} CANNOT be found !!"
}

"DONE"

// vim:tabstop=2:softtabstop=2:shiftwidth=2:expandtab:filetype=Groovy

with output

#!/usr/bin/env groovy

import hudson.plugins.git.GitSCM
import hudson.plugins.git.UserRemoteConfig
import org.jenkinsci.plugins.workflow.job.WorkflowJob
import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
import com.cloudbees.plugins.credentials.common.StandardCredentials
import com.cloudbees.plugins.credentials.CredentialsProvider

String newCredId = 'ED25519_SSH_CREDENTIAL'
String orgCredId = ''
String newUrl    = ''
String orgUrl    = ''

if ( CredentialsProvider.lookupCredentials( StandardCredentials.class, jenkins.model.Jenkins.instance)
                        .any { newCredId == it.id }
) {

  Jenkins.instance.getAllItems( WorkflowJob.class ).findAll {
    it.definition instanceof org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition &&
    ! it.definition?.scm?.userRemoteConfigs.collect { it.credentialsId }.contains( newCredId )
  }.each { job ->

    GitSCM orgScm          = job.definition?.scm
    Boolean orgLightweight = job.definition?.lightweight

    List<UserRemoteConfig> newUserRemoteConfigs = orgScm.userRemoteConfigs.collect {
      orgUrl    = it.url
      newUrl    = 'ssh://' + it.url.split('ssh://').last().split('@').last()
      orgCredId = it.credentialsId
      new UserRemoteConfig( newUrl, it.name, it.refspec, newCredId )
    }
    GitSCM newScm = new GitSCM( newUserRemoteConfigs, orgScm.branches, orgScm.doGenerateSubmoduleConfigurations,
                                orgScm.submoduleCfg, orgScm.browser, orgScm.gitTool, orgScm.extensions
                              )
    CpsScmFlowDefinition flowDefinition = new CpsScmFlowDefinition( newScm, job.definition.scriptPath )

    job.definition = flowDefinition
    job.definition.lightweight = orgLightweight
    job.save()
    println ">> " + job.fullName + " DONE :" +
            "\n\t - orgScm: ${(orgCredId ?: '').padRight(30)}: ${orgUrl}" +
            "\n\t - newScm: ${(newCredId ?: '').padRight(30)}: ${newUrl}"
  }

} else {
  println "${newCredId} CANNOT be found !!"
}

"DONE"

// vim:tabstop=2:softtabstop=2:shiftwidth=2:expandtab:filetype=Groovy

disable all particular projects jobs

List<String> projects = [ 'project-1', 'project-2', 'project-n' ]

Jenkins.instance.getAllItems(Job.class).findAll {
  projects.any { p -> it.fullName.startsWith(p) }
}.each {
  println "~~> ${it.fullName}"
  it.disabled = true
  it.save()
}

undo disable jobs in particular projects

List<String> projects = [ 'project-1', 'project-2', 'project-n' ]

Jenkins.instance.getAllItems(Job.class).findAll {
  it.disabled && projects.any{ p -> it.fullName.startsWith(p) }
}.each {
  println "~~> ${it.fullName}"
  it.disabled = false
  it.save()
}
Copyright © marslo 2020-2023 all right reserved,powered by GitbookLast Modified: 2024-03-27 16:56:10

results matching ""

    No results matching ""