• Stars
    star
    325
  • Rank 124,274 (Top 3 %)
  • Language
    Groovy
  • Created almost 6 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“– Groovy CheatSheet For Jenkins Usage In A4

1 CheatSheet: Jenkins & Groovy

linkedin
github
slack


PRs Welcome

File me Issues or star this repo.

1.1 Jenkins Pipeline

NameComment
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..")
List all Jenkins plugins and versionslist-all-plugins.groovy
Check whether property existsif (env.keep_failed_env)
Jenkins Pipeline enable timestampsoptions{timestamps()}
Set envs within a jenkins pipelinewithEnv(["key1=$var1"])
Install plugin via groovyHudson.instance.updateCenter.getPlugin(plugin).deploy().get()
Keep previous job run via groovybuildDiscarder(logRotator(daysToKeepStr: '20', numToKeepStr: '60'))
Customize job workspace=customWorkspace β€œ/some/other/path”=
git scm checkout to relative directoryextensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'XXX']]
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: Groovy Language Documentation
ReferenceLink: Example, Link: Example

1.2 Config Jenkins Via Groovy

NameComment
Set timezone for jenkinstimezone.groovy
Set timezone for jenkinsSystem.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', 'America/Los_Angeles')
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
Configure only 1 executor per workerFor each agent, configure # of executors
Configure slack pluginconfig-slack.groovy
Configure pipeline shared librariesconfig-pipeline-library.groovy
Get jenkins version from CLIjava -jar /usr/share/jenkins/jenkins.war --version
ReferenceGitHub: cloudbees/jenkins-scripts, GitHub: jenkinsci/pipeline-examples

1.3 Jenkins Trouble Shooting

NameComment
List performance metrics for each Jenkins agentslist-all-jenkins-agent.sh

1.4 Jenkins Kubernetes Via Groovy

NameComment
Config jenkins kubernetes pluginjenkins-kubernetes-cloud.groovy
Validate Kubernetes jenkins setupvalidate-kubernetes-cloud.groovy
Kubernetes run with envs configuredrunWithEnvVariables.groovy
ReferenceGitHub: kubernetes-plugin pipeline examples

1.5 Jenkins View Via Groovy

NameComment
Add a list of jobs by regexp to a viewmyView.setIncludeRegex(".*Integration.*"), addjobstoview-byregexp.groovy
Create jenkins views and add jobs to itjenkins-views.groovy
Add a view of build monitor view pluginbuild-monitor-views.xml
Change view description in groovymyView.doSubmitDescription

1.6 Jenkins Job Via Groovy

NameComment
List all my jenkins jobsprintln Jenkins.instance.projects.collect { it.name }
List all jenkins jobslist-all-jobs.groovy
Create and trigger a jobcreate-jenkins-job.groovy
Manage jenkins jobsmanage-jenkins-jobs.groovy
Cancel queued jenkins jobs by regexpkill-queued-jenkins.groovy
Support HTML for job and parameter descriptionsLink: OWASP Markup Formatter Plugin

1.7 Jenkins Different Parameters

NameComment
stringstring(name: 'key1', defaultValue: 'Default value', description: 'some parameter')
texttext(name: 'key1', defaultValue: 'Default value', description: 'some parameter')
booleanbooleanParam(name: 'key1', defaultValue: true, description: 'some parameter')
choicechoice(name: 'key1', choices: 'One\nTwo\nThree\n', description: 'some parameter')
passwordpassword(name: 'key1', defaultValue: 'SECRET', description: 'Enter a password')
filefile(name: 'key1', description: 'Choose a file to upload')

1.8 Jenkins Security Via Groovy

NameComment
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
Jenkins skip wizzard when initializationinstance.setInstallState(InstallState.INITIAL_SETUP_COMPLETED)
Slave To Master Access Control00-slave-to-master-access.groovy
CSRF Protection00-csrf.groovy
Add Jenkins permissionjenkins-permission.groovy
Disable CLI over Remoting00-disable-cli-remoting.groovy
Disable jnlpjenkins.setSlaveAgentPort(-1)
Access Control for Buildsjenkins.security.QueueItemAuthenticatorConfiguration.xml

1.9 Load Jenkins settings via folder copy

NameComment
Add default jobsCopy jobs/ /usr/share/jenkins/ref/jobs/
Copy custom built pluginsCOPY plugins/*.hpi /usr/share/jenkins/ref/plugins/
Use jenkins cliCOPY config/jenkins.properties /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/install-plugins.sh < /usr/share/jenkins/ref/plugins.txt

1.10 Jenkins Plugins

PluginSummary
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
Log Parser PluginParse the console output and highlight error/warning/info lines.
Build-timeout PluginAbort if job takes too long
Naginator PluginRetry failed a job
ThinBackup PluginBackup jenkins
JobConfigHistory PluginBackup job configuration
β€œAnything Goes” formatteruse JavaScript inside your project description
AnsiColor PluginAdd support for ANSI escape sequences, including color, to Console Output
Build User Vars PluginDescribe the user who started the build
Gitlab PluginAllows GitLab to trigger Jenkins builds
Workspace CleanupPlugin to delete the build workspace.
UpdateSites Manager pluginmanage update sites, where Jenkins accesses in order to retrieve plugins

1.11 Jenkins Git Via Groovy

NameComment
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.12 Jenkins networking Via Groovy

NameComment
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.13 Jenkins with Kubernetes/Docker

NameComment
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
Jenkins customize docker build args=additionalBuildArgs β€˜β€“build-arg SSH_PRIVATE_KEY…’=

1.14 Groovy Common Errors/Exceptions

NameComment
Illegal class nameJVM doesn’t like class names with a hyphen

1.15 Groovy Basic

Name Comment
Get environment variables get-env.groovy, println env.WORKSPACE
Groovy execute command execute-command.groovy
Get data type of a variable myObject.getClass()
Print stdout print.groovy echo β€˜Action is done’, println β€œHello World”
Use boolean parameter if (istrue == β€œfalse”) {…}
Basic integer caculation def a = 3, b = 7; println β€œ$a + $b = ${a + b}”
Run groovy online SaaS: Groovy Web console
Run groovy script from Jenkins Link: Jenkins Script Console
Reference Link: Apache Groovy

1.16 Groovy String

Name Comment
Check string startsWith assert s.startsWith("\t")
Trim whitespaces s=s.trim()
Concat string first = 'Joe'; last = 'Smith'; println("Name: $first $last")
Convert list to string l.join(";")
Create string with multi-lines multi-line-string.groovy
Convert string to list split-string.groovy
Convert string to json string-to-json.groovy
Remove tags input.replaceAll("\\<.*?>","")
Regex match regexp-match.groovy

1.17 Groovy Regexp

NameComment
Regex case insensitive(item.name == ~/(?i).*NSX.*/ )
ReferenceRegular Expressions in Groovy

1.18 Groovy Array

NameComment
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.19 Groovy File

NameComment
Read file into a stringString fileContents = new File('/tmp/test.txt).text
Read file content as a variabledef env = System.getenv(), def content = readFile("/tmp/test.txt")
Write file in pipelinewriteFile file: β€œoutput/my.txt”, text: β€œThis is a test”
Read a property filedef conf = readProperties file: β€œ${env.WORKSPACE}@script/my.properties”
Read and write json filesjson-file.groovy
Obtain a relative pathrelative-path.groovy

1.20 Groovy Shell Command

NameComment
Run shell and get outputdef out = sh script: command, returnStdout: true
Run shell and get exit codedef status = sh script: command, returnStatus: true

1.21 Groovy Dictionary

NameComment
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.22 Groovy json

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

1.23 Groovy Date

NameComment
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.24 Jenkins Agent

NameComment
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.25 Jenkins Maintenance

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

1.26 More Resources

http://groovy-lang.org/documentation.html#gettingstarted

https://github.com/fabric8io/jenkins-docker

License: Code is licensed under MIT License.

linkedin github slack

More Repositories

1

cheatsheet-kubernetes-A4

πŸ“– Kubernetes CheatSheets In A4
Shell
1,851
star
2

cheatsheet.dennyzhang.com

Apply best practices via CheatSheets
Shell
649
star
3

kubernetes-yaml-templates

Kubernetes Yaml Templates
594
star
4

challenges-kubernetes

☁️ Challenges Your Kubernetes Skills And Knowledge
Shell
230
star
5

devops_public

🎩 DevOps Scripts
Shell
178
star
6

cheatsheet-gcp-A4

☁️ GCP gcloud, gsutil, etc.
110
star
7

cheatsheet-python-A4

πŸ“– Advanced Python Syntax In A4
Python
100
star
8

code.dennyzhang.com

❓ Algorithms & Coding Problems
CSS
95
star
9

cheatsheet-docker-A4

πŸ“– Docker CheatSheets In A4
Dockerfile
90
star
10

monitor-docker-slack

⏰ Get Slack Notifications, When Containers Run Into Issues
Python
71
star
11

challenges-cloudformation-jenkins

🏫 Challenges Your AWS And Cloudformation Skills By Solving Real Questions.
Shell
60
star
12

cheatsheet-golang-A4

πŸ“– Advanced Golang Syntax In A4
Go
56
star
13

prepare-k8s-cka

πŸ“– Preparation For Kubernetes CKA/CKAD Exam
51
star
14

cheatsheet-aws-A4

☁️ AWS CheatSheets In A4
48
star
15

cheatsheet-paper-A4

https://cheatsheet.dennyzhang.com/cheatsheet-paper-A4
46
star
16

Denny-s-emacs-configuration

πŸ€– Emacs shapes me to be a better programmer
Emacs Lisp
41
star
17

kubernetes-scripts

Handy kubernetes scripts for common scenarios
Shell
37
star
18

challenges-chef

πŸ“– Challenges Your Chef Skills By Solving Real Questions.
Ruby
26
star
19

cheatsheet-git-A4

CheatSheet For Git & GitHub
25
star
20

developer-free-saas

πŸ•ΈοΈ A curated list Of Free Web-based Tools For Developers
Shell
23
star
21

devops_jenkins

πŸ€– VisualOps via Jenkins jobs
21
star
22

architect.dennyzhang.com

☝️ Learn system design in a solid way
Shell
21
star
23

cheatsheet-tmux-A4

tmux/tmate Usage in A4
20
star
24

cheatsheet-vim-A4

Vim usage and personal knowledge base
18
star
25

cheatsheet-pks-A4

CheatSheet For PKS: Pivotal Kubernetes Service
Shell
16
star
26

popular-github-template

πŸ“— Repo Template: Make Your GitHub Repos More Popular
16
star
27

cheatsheet-shell-A4

🏫 Examine your shell skills
Shell
16
star
28

xiaozibao

Your personal magzine, adjusted by your taste.
Objective-C
13
star
29

python-selenium

Use Python Selenium For GUI Automation Test
Python
11
star
30

cheatsheet-bosh-A4

πŸ“– CheatSheet For CloudFoundry Bosh
Shell
10
star
31

remote-commands-servers

πŸ‘ͺ Run remote ssh commands on multiple servers
Python
9
star
32

monitoring

Checks for various monitoring
Shell
9
star
33

chatops_slack

πŸš€ Python Slack ChatOps
Python
7
star
34

elasticsearch-cli-tool

πŸͺ CLI tools for ealsticsearch
Python
6
star
35

developer-technical-selling

πŸ’΅ Do a better technical selling as a developer
5
star
36

linkedin-grow-influence

πŸ”Œ How To Improve Professional Influence In Linkedin
5
star
37

challenges-k8s-monitoring

Notes for deep dive into Kubernetes monitoring
5
star
38

cheatsheet-emacs-A4

πŸ“– Emacs lisp cheatsheet
Emacs Lisp
5
star
39

challenges-aws-ecs

✍️ Case study using AWS ECS to setup personal wordpress
PHP
5
star
40

detect_suspicious_process

Detect suspicious process
Python
4
star
41

challenges-k8s-crd

Kubernets CRD: extend k8s resource
Dockerfile
4
star
42

cheatsheet-ruby-A4

πŸ“– Advanced Ruby Syntax In A4
4
star
43

directory-cli-tool

πŸ“ CLI tools for directories
Shell
3
star
44

python-hosts-tool

πŸ“ Manage /etc/hosts in an organized way by Python
Python
3
star
45

code-with-docker

Use docker to write code in different languages
Shell
3
star
46

www.dennyzhang.com

Personal blog: DevOps, Cloud, Life
Shell
3
star
47

challenges-k8s-logging

Notes for deep dive into Kubernetes logging
3
star
48

challenges-k8s-storage

Notes for deep dive into Kubernetes storage
3
star
49

maintain-github-repos

πŸ‘ͺ KnowledgeBase: Grow Influence From Maintaining Github Projects
3
star
50

maintain-it-blog

πŸ“š Be a better IT Blogger
3
star
51

chef_community_cookbooks

πŸ– Chef cookbooks for devops
Python
3
star
52

nmap-scan-docker

nmap network scan via docker
Python
3
star
53

shadowsocks-vpn-docker

πŸ—οΈ Docker shadowsocks VPN
Shell
2
star
54

dennytest

Github Repo to host various test scripts
Go
2
star
55

jenkins_image

πŸ’‚β€β™‚οΈ Jenkins Docker Image
Shell
2
star
56

my-slides

Host my slides: devops, kubernetes, life, etc
2
star
57

cleanup_old_files

Clean old files in an organized way
Python
2
star
58

terraform_jenkins_digitalocean

Define Jenkins job to create and provision digitalocean VMs by terraform
Shell
2
star
59

cheatsheet-living-in-ca

πŸ‘ͺ CheatSheet for living in Canifornia
2
star
60

python-aws-cli-wrapper

☁️ Wrapper layer of AWS CLI in Python
Python
2
star
61

quiz.dennyzhang.com

πŸ“– Examine skills in a hard way
Shell
1
star
62

dennyzhang.github.io

dummy website
1
star
63

check_logfiles

nagios plugin to check log files
Perl
1
star
64

book-reading-cloud

πŸ“– My book reading to be a good cloud engineer/architect
1
star
65

couchbase-cli-tool

Couchbase CLI Tools
Python
1
star
66

node_status_in_json

Query node status and return a structured json
Python
1
star
67

challenges-fluent-bit

Deep dive into fluent-bit
1
star
68

today-learning

Personal memo for #today-learnings in our DevOps slack group
1
star