Skip to content
📖 Groovy CheatSheet For Jenkins Usage In A4
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore update doc Sep 5, 2018 jenkins configure url May 14, 2019
check-slave-jar-version.groovy more groovy scripts May 6, 2019
config-slack.groovy more groovy scripts May 1, 2019
create-jenkins-job.groovy groovy scripts May 1, 2019
create-jenkins-user.groovy more groovy scripts May 6, 2019
create-secret-text.groovy more groovy scripts May 6, 2019
delete-job-by-regexp.groovy more groovy scripts May 6, 2019
docker-cleanup.groovy more groovy scripts May 6, 2019
enable-ldap.groovy more groovy scripts May 6, 2019
files-folder.groovy more groovy scripts May 6, 2019
find-dead-executors.groovy jenkins agent May 1, 2019
get-env.groovy more groovy scripts May 1, 2019
get-ip-by-hostname.groovy update groovy Apr 30, 2019
git-checkout.groovy more groovy scripts May 6, 2019
git-commits-before-fail.groovy more groovy scripts May 6, 2019
git-list-tags-and-branches.groovy more groovy scripts May 6, 2019
jenkins-kubernetes-cloud.groovy more groovy scripts May 6, 2019
jenkins-url.groovy jenkins configure url May 14, 2019
jenkinsfile-finally.groovy update groovy Apr 30, 2019
jenkinsfile-parallelly.groovy update groovy Apr 30, 2019
jenkinsfile-pass-parameter.groovy update groovy Apr 30, 2019
jenkinsfile-sequentially.groovy update groovy Apr 30, 2019
jenkinsfile-timeout-retry.groovy update groovy Apr 30, 2019
json-file.groovy more groovy scripts May 6, 2019
keep-going-with-errors.groovy update groovy Apr 30, 2019
kill-queued-jenkins.groovy rename groovy script May 7, 2019
list-all-jobs.groovy groovy to list all jobs May 8, 2019
loop-map.groovy update groovy Apr 30, 2019
manage-jenkins-jobs.groovy more groovy scripts May 6, 2019
master-executors.groovy more groovy scripts May 6, 2019
matrix-authorization-strategy.groovy more groovy scripts May 6, 2019
regexp-match.groovy more groovy scripts May 6, 2019
relative-path.groovy groovy scripts May 1, 2019
set-agent-env.groovy groovy to list all jobs May 8, 2019
slack-notification.groovy update groovy Apr 30, 2019
timezone.groovy delete useless file Feb 17, 2019

1 CheatSheet: Jenkins & Groovy


PRs Welcome

File me Issues or star this repo.

1.1 Jenkins Pipeline

Specify parameter to run jobsbuild job:'job1', parameters:[string(name:'name1', value:va1)]
Run job in different agentsnode($agent_label) {...}
Ask for user inputstage('stage2'){ input "OK to go?" }
Actively fail current pipeline joberror("Build failed because of this and that..")
Keep going when previous stage has failedkeep-going-with-errors.groovy
Send slack notification in pipelineslack-notification.groovy
Pass parameter across jenkins jobsjenkinsfile-pass-parameter.groovy
Set timeout & retryjenkinsfile-timeout-retry.groovy
Use finally to do cleanupjenkinsfile-finally.groovy
Run jenkins jobs in a sequential wayjenkinsfile-sequentially.groovy
Run jenkins jobs in paralleljenkinsfile-parallelly.groovy
ReferenceLink: Syntax Reference, Link: Jenkins User Documentation
ReferenceLink: Example, Link: Example

1.2 Config Jenkins Via Groovy

Set timezone for jenkinstimezone.groovy
Configure default viewjenkins-views.groovy
Configure Jenkins urljenkins-url.groovy
Create a Jenkins usercreate-jenkins-user.groovy
Groovy manages files/foldersfiles-folder.groovy
Configure max executors in Jenkinsmaster-executors.groovy
Config jenkins kubernetes pluginjenkins-kubernetes-cloud.groovy
Configure slack pluginconfig-slack.groovy
ReferenceGitHub: cloudbees/jenkins-scripts, GitHub: jenkinsci/pipeline-examples

1.3 Jenkins Job Via Groovy

List all my jenkins jobsprintln Jenkins.instance.projects.collect { }
List all jenkins jobslist-all-jobs.groovy
Add a list of jobs by regexp to a viewaddjobstoview-byregexp.groovy
Create jenkins views and add jobs to itjenkins-views.groovy
Create and trigger a jobcreate-jenkins-job.groovy
Manage jenkins jobsmanage-jenkins-jobs.groovy
Cancel queued jenkins jobs by regexpkill-queued-jenkins.groovy

1.4 Jenkins Security Via Groovy

logged-in users can do anythinglogged-in-users.groovy
Enable ldap in Jenkinsenable-ldap.groovy
Create a jenkins secret textcreate-secret-text.groovy
Configure authorization in Jenkinsmatrix-authorization-strategy.groovy
Jenkins skip wizzard when initialization-Djenkins.install.runSetupWizard=false

1.5 Load Jenkins settings via folder copy

Add default jobsCopy jobs/ /usr/share/jenkins/ref/jobs/
Copy custom built pluginsCOPY plugins/*.hpi /usr/share/jenkins/ref/plugins/
Use jenkins cliCOPY config/ /usr/share/jenkins/ref/
Add jenkins groovy scriptsCOPY config/*.groovy /usr/share/jenkins/ref/init.groovy.d/
Configure Jenkins with some defaultsCOPY config/*.xml /usr/share/jenkins/ref/
Install jenkins plugins/usr/local/bin/ < /usr/share/jenkins/ref/plugins.txt

1.6 Jenkins Plugins

Kubernetes PluginJenkins plugin to run dynamic agents in a Kubernetes/Docker environment
Credentials PluginLoad the ssh key
SiteMonitor PluginMonitor URLs
Timestamper PluginAdd timestamp to job output
Dashboard View PluginCreate dashboard
Build-timeout PluginAbort if job takes too long
Naginator PluginRetry failed a job
ThinBackup PluginBackup jenkins
JobConfigHistory PluginBackup job configuration
Build User Vars PluginDescribe the user who started the build

1.7 Jenkins Git Via Groovy

Git checkout codegit-checkout.groovy
Get all git commits since last successgit-commits-before-fail.groovy
List git tags and branchesgit-list-tags-and-branches.groovy

1.8 Jenkins networking Via Groovy

Get hostnameprintln InetAddress.localHost.canonicalHostName
Get IP addressprintln InetAddress.localHost.hostAddress
Get hostname by ipget-ip-by-hostname.groovy
validate user input: ip addressassert ip_address.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")

1.9 Jenkins with Kubernetes/Docker

Kubernetes PluginJenkins plugin to run dynamic agents in a Kubernetes/Docker environment
Config jenkins kubernetes pluginjenkins-kubernetes-cloud.groovy
Cleanup for Docker stale containers/images/volumesdocker-cleanup.groovy

1.10 Groovy Basic

Get environment variablesget-env.groovy
Groovy execute commandexecute-command.groovy
Print stdoutprint.groovy echo ‘Action is done’, println “Hello World”
Use boolean parameterif (istrue == “false”) {…}
Basic integer caculationdef a = 3, b = 7; println “$a + $b = ${a + b}”
Run groovy onlineSaaS: Groovy Web console
Run groovy script from JenkinsLink: Jenkins Script Console
ReferenceLink: Apache Groovy

1.11 Groovy String/Regexp

Convert list to stringl.join(";")
Create string with multi-linesmulti-line-string.groovy
Convert string to listsplit-string.groovy
Convert string to jsonstring-to-json.groovy
Remove tagsinput.replaceAll("\\<.*?>","")
Regex matchregexp-match.groovy

1.12 Groovy Array

Iterate a listfor(item in [1,2,3,4]){ println item }
Iterate a list(1..3).each { println "Number ${it}"}
Add item to listdef alist = [10, 9, 8]; alist << 7
List sizedef alist = [10, 9, 8]; alist.size()
Split string with delimiter=’1128-2’.tokenize( ‘-’ )=

1.13 Groovy File

Read file content as a variabledef env = System.getenv(), def content = readFile("/tmp/test.txt")
Read and write json filesjson-file.groovy
Obtain a relative pathrelative-path.groovy

1.14 Groovy Dictionary

Create a mapdef m = ['fruit':'Apple', 'veggie':'Carrot']
Add an item to mapm.put('denny','hello')
Check if key existsm.containsKey('key1')
Loop a maploop-map.groovy

1.15 Groovy json

Convert string to jsonstring-to-json.groovy
Convert dictionary to jsondict-to-json.groovy
Read and write json filesjson-file.groovy

1.16 Groovy Date

Date to stringnew Date().format("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"))
String to dateDate.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", "2001-01-01T00:00:00Z")
String to dateDate.parse("yyyy-MM-dd'T'HH:mm:ssZ", "2001-01-01T00:00:00+0000")

1.17 Jenkins Agent

Check jenkins slave jar versioncheck-slave-jar-version.groovy
Find dead executors and remove themfind-dead-executors.groovy
Set env for each agentset-agent-env.groovy

1.18 Jenkins Maintenance

Delete jenkins job by regexpdelete-job-by-regexp.groovy
Deploy Jenkins via docker
Clean up old buildsLink: CloudBees Best Strategy for Disk Space Management

1.19 More Resources

License: Code is licensed under MIT License.

linkedin github slack
You can’t perform that action at this time.