Jenkins

<< Back to wiki homepage

(I must say here, I hate this glorified cronjob scheduler named Jenkins. But if you're stuck with it, I hope I could help a bit with this page.)

Table of contents:

Grepping jenkins configs

grep -Hni ${whatever_you_are_searching} ${JENKINS_HOME}/jobs/*/config.xml

Groovy Snippets

These can work on: https://${your_jenkins_host}/script

Decrypt saved credentials

Get the password from ${JENKINS_HOME}/credentials.xml

println( hudson.util.Secret.decrypt("${PUT_ENCRYPTED_PASSPHRASE_OR_PASSWORD_HERE}") )
import java.nio.charset.StandardCharsets;
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
      com.cloudbees.plugins.credentials.Credentials.class
)

for (c in creds) {
  println(c.id)
  if (c.properties.description) {
    println("   description: " + c.description)
  }
  if (c.properties.username) {
    println("   username: " + c.username)
  }
  if (c.properties.password) {
    println("   password: " + c.password)
  }
  if (c.properties.passphrase) {
    println("   passphrase: " + c.passphrase)
  }
  if (c.properties.secret) {
    println("   secret: " + c.secret)
  }
  if (c.properties.secretBytes) {
    println("    secretBytes: ")
    println("\n" + new String(c.secretBytes.getPlainData(), StandardCharsets.UTF_8))
    println("")
  }
  if (c.properties.privateKeySource) {
    println("   privateKey: " + c.getPrivateKey())
  }
  if (c.properties.apiToken) {
    println("   apiToken: " + c.apiToken)
  }
  if (c.properties.token) {
    println("   token: " + c.token)
  }
  println("")
}

List plugins

Jenkins.instance.pluginManager.plugins.each{
  plugin ->
    println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()}")
}

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()

Connect to slaves and run groovy code / shell command on them

import hudson.util.RemotingDiagnostics
import jenkins.model.Jenkins

String agent_name = 'macpro15'
//groovy script you want executed on an agent
groovy_script = '''
def get = new URL("http://apk-versioning.forgeofempires.com:8080/microversion/1.208").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if (getRC.equals(200)) {
    println(get.getInputStream().getText());
}
'''.trim()

String result
Jenkins.instance.slaves.find { agent ->
    agent.name == agent_name
}.with { agent ->
    result = RemotingDiagnostics.executeGroovy(groovy_script, agent.channel)
}
println result

(if you want to run shell command, replace inline script with something like this:

def proc = "my command to run".execute(null, new File("folder to run inside"))
//folder part is optional, you can also just use execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)

println proc.text
println b.toString()

Generate a jenkins token in behalf of a user

Of course you need to have the permission to do this (e.g. admin). Especially helpful for service accounts.

import hudson.model.*
import jenkins.model.*
import jenkins.security.*
import jenkins.security.apitoken.*

def userName = '{YOUR_USER}'
def tokenName = '{YOUR_TOKEN_NAME}'

def user = User.get(userName, false)
def apiTokenProperty = user.getProperty(ApiTokenProperty.class)
def result = apiTokenProperty.tokenStore.generateNewToken(tokenName)
user.save()

return result.plainValue