Skip to content

Instantly share code, notes, and snippets.

@mikejoh
Last active April 6, 2023 15:25
Show Gist options
  • Save mikejoh/9a721d1e6de7574059dcb8f851692be9 to your computer and use it in GitHub Desktop.
Save mikejoh/9a721d1e6de7574059dcb8f851692be9 to your computer and use it in GitHub Desktop.
Random useful Jenkins and Groovy script snippets

Jenkins Groovy good-to-have snippets

Example of printing all properties of an object

import java.lang.System
import hudson.model.*
import jenkins.model.*
import com.cloudbees.jenkins.plugins.bitbucket.endpoints.*

def home_dir = System.getenv("JENKINS_HOME")
def properties = new ConfigSlurper().parse(new File("$home_dir/jenkins.properties").toURI().toURL())

def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration")

for (item in desc.getEndpoints()) {
 	println item.getProperties().toString()
}

Print all environment variables

def envVars = Jenkins.instance.getGlobalNodeProperties().get(0).getEnvVars()
println envVars

Change array elements on the fly

def env_no_proxy = "localhost,127.0.0.1,.internaldomain.com"

no_proxy = env_no_proxy.split(',').collect{ proxy_conf -> 
  if (!proxy_conf.contains('*.internaldomain')) {
    proxy_conf.replace('.internaldomain','*.internaldomain')
  } else {
    proxy_conf = proxy_conf
  }
}.join(',')

Fake properties that would be read from file (used from Script Console) during development/testing

def instance = Jenkins.getInstance()
def home_dir = System.getenv("JENKINS_HOME")
def properties = new ConfigSlurper().parse("""

mysettings {
  enabled = true
  http_proxy_host = "http://myproxy.com"
  http_proxy_port = 80
  no_proxy = "localhost,127.0.0.1"
}

""")

if (properties.mysettings.enabled) {
    http_proxy_host = properties.mysettings.http_proxy_host
    http_proxy_port = properties.mysettings.http_proxy_port
{

def proxy_conf = new hudson.ProxyConfiguration(http_proxy_host, http_proxy_port)
instance.proxy = proxy_conf
instance.save()

Fetch all currently installed plugins from a Jenkins Master instance (via the API)

Useful to run and populate a new plugins.txt file for installing via plugins.sh

#!/bin/bash

JENKINS_HOST="$1"
JENKINS_PORT="8080"

echo "Fetching installed plugins.."

curl -sSL "http://${JENKINS_HOST}:${JENKINS_PORT}/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins" | perl -pe 's/.*?<shortName>([\w-]+).*?<version>([^<]+)()(<\/\w+>)+/\1 \2\n/g'|sed 's/ /:/'

Fetch all currently installed plugins from a Jenkins Master instance (via Script Console)

plugins = [:]
jenkins.model.Jenkins.instance.getPluginManager().getPlugins().each {plugins << ["${it.getShortName()}":"${it.getVersion()}"]}
plugins.sort().each() { println "${it.key}:${it.value}"}

Remote reload of CasC plugin with a groovy script sent to the script console

For testing purposes i disabled CSRF since i didnt get this to work with the API token. At the time of writing this that groovy script will end up in a Null Pointer exception due to the doReload() method not sanitizing input correctly.

doReload.groovy

org.jenkinsci.plugins.casc.ConfigurationAsCode.get().doReload(null, null)

Reload with curl:

curl -u "<user>:<password>" --data-urlencode "script=$(<./doReload.groovy)" http://localhost:8080/scriptText

Add your own views (with View config in a property file), this was done via the Script Console

def instance = Jenkins.getInstance()
def home_dir = System.getenv("JENKINS_HOME")
def properties = new ConfigSlurper().parse("""
views {
  enabled = true
  config {
    jenkins {
    name = "Jenkins"
      regexp = ".*jenkins.*"
    }
    infra_pipelines {
      name = "Infrastructure Pipelines"
      regexp = "esw.*-pipeline"
    }
    retentions {
      name = "Retention Jobs"
      regexp = ".*[Rr]etention.*"
    }
  }
}
""")

properties.views.each {
	if(!instance.getView(it.value.name)) {
		instance.addView(new ListView(it.value.name))
		def view = instance.getView(it.value.name)
		view.setIncludeRegex(it.value.regexp)
	}
}

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