Jenkins

Table of contents:

Grepping jenkins configs

grep -Hni field_revision_field_tags /var/lib/jenkins/jobs/*/config.xml

Groovy Snippets

Find workspaces

def hi = hudson.model.Hudson.instance
hi.getItems(hudson.model.Job).each {
job ->
  if (job.getClass() != org.jenkinsci.plugins.workflow.job.WorkflowJob) {
    if (job.workspace != null) {
        println(job.workspace)
    }
  } else {
    println("/var/lib/jenkins/" + job.getDisplayName())
  }
}

Show non-discarded jobs

import jenkins.model.Jenkins
import hudson.model.Job
import jenkins.model.BuildDiscarderProperty
import hudson.tasks.LogRotator

Jenkins.instance.allItems(Job).each { job ->
    if (job.isBuildable() && job.supportsLogRotator() && job.getProperty(BuildDiscarderProperty) == null) {
      println "${job.fullDisplayName}"
    }
}
return;

List branches of a git repository

def user = "jenkins-credential-user";
def url = "some git url ending with .git";

import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins

def creds = CredentialsProvider.lookupCredentials(
    StandardUsernamePasswordCredentials.class,
    Jenkins.instance
);

def c = creds.findResult { it.username == user ? it : null }
def pass = c.password;

def repo = "https://" + user + ":" + pass + "@" + url;

return ["/bin/bash", "-c", "git ls-remote -h " + repo + " | sed 's/.*refs\\/heads\\/\\(.*\\)/\\1/'"].execute().text.tokenize();

Run command and get result lines as list

def runCommand = { strList ->
  assert ( strList instanceof String ||
           ( strList instanceof List && strList.each{ it instanceof String } ) \
)
  def proc = strList.execute()
  result_dict = []
  proc.in.eachLine { line -> result_dict += line }
  proc.out.close()
  proc.waitFor()

  print "[INFO] ( "
  if(strList instanceof List) {
    strList.each { print "${it} " }
  } else {
    print strList
  }
  println " )"

  if (proc.exitValue()) {
    println "gave the following error: "
    println "[ERROR] ${proc.getErrorStream()}"
  }
  assert !proc.exitValue()

  return result_dict
}

runCommand(['some_command', '-parameter'] ).unique().sort()