Jenkins Cheat Sheet

Posted : admin On 1/1/2022

An MSBuild Cheatsheet of handy references I’ve used for automating with MSBuild. Reference Paths. Specify the path(s) to Project Reference DLLs. 'Cheatsheet Jenkins Groovy A4' and other potentially trademarked words, copyrighted images and copyrighted readme contents likely belong to the legal entity who owns the '. Jenkins could make a lot of sense despite his higher draft position over/under, and the teams picking in the 17-22 range certainly suggest the value lies on his Under. If they don't like the OL options, linebacker makes sense on the defensive side of the ball. Jenkins Cheat Sheet by FunThomas424242 - Cheatography.com Created Date: 1605Z. This handy cheat sheet gives you all the essentials you need to know. Including how to install and manage Jenkins using Docker, pipeline concepts, job types, examples and the top Jenkins plugins for DevOps in 2021. Jenkins is an open source automation tool written in Java with plugins built for Continuous Integration purposes.

  1. Jenkins Declarative Pipeline Cheat Sheet
  2. Jenkins Cheat Sheet Pdf
  3. Jenkins Cheat Sheet Pdf
  4. Jenkins File Cheat Sheet


  • PDF Link: cheatsheet-jenkins-groovy-A4.pdf, Category: languages
  • Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-A4
  • Related posts: Jenkins CheatSheet, #denny-cheatsheets

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..')
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 workspacecustomWorkspace '/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: 'OnenTwonThreen', 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 argsadditionalBuildArgs '--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

NameComment
Get environment variablesget-env.groovy, println env.WORKSPACE
Groovy execute commandexecute-command.groovy
Get data type of a variablemyObject.getClass()
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.16 Groovy String/Regexp

NameComment
Check string startsWithassert s.startsWith('t')
Trim whitespacess=s.trim()
Concat stringfirst = 'Joe'; last = 'Smith'; println('Name: $first $last')
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
Regex case insensitive(item.name ~/(?i).*NSX.*/ )
ReferenceRegular Expressions in Groovy

1.17 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.18 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.19 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
Jenkins Cheat Sheet

1.20 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.21 Groovy json

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

Jenkins Declarative Pipeline Cheat Sheet

1.22 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.23 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.24 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.25 More Resources

License: Code is licensed under MIT License.


Jenkins Cheat Sheet Pdf

(from Understanding Nginx Server and Location Block Selection Algorithms - https://goo.gl/YyzshP)

Blocks: server

Priority

  1. listen
  2. server_name

Directives: listen

The listen directive can be set to:

  • An IP address/port combo.
  • A lone IP address which will then listen on the default port 80.
  • A lone port which will listen to every interface on that port.
  • The path to a Unix socket.

When 'incomplete' listen directives

  • A block with no listen directive uses the value 0.0.0.0:80.
  • A block set to an IP address 111.111.111.111 with no port becomes 111.111.111.111:80
  • A block set to port 8888 with no IP address becomes 0.0.0.0:8888

Options: default_server

Directives: server_name

Nginx evaluates these by using the following formula:

  • Nginx will first try to find a server block with a server_name that matches the value in the 'Host' header of the request exactly.
  • Find a server block with a server_name that matches using a leading wildcard (indicated by a * at the beginning of the name in the config).
  • If no match is found using a leading wildcard, Nginx then looks for a server block with a server_name that matches using a trailing wildcard (indicated by a server name ending with a * in the config).
  • If no match is found using a trailing wildcard, Nginx then evaluates server blocks that define the server_name using regular expressions (indicated by a ~ before the name).
  • If no regular expression match is found, Nginx then selects the default server block for that IP address and port.

Blocks: location

Options: optional_modifier

  • (none): The location is interpreted as a prefix match. This means that the location given will be matched against the beginning of the request URI to determine a match.
  • =: This block will be considered a match if the request URI exactly matches the location given.
  • ~: This location will be interpreted as a case-sensitive regular expression match.
  • ~*: The location block will be interpreted as a case-insensitive regular expression match.
  • ^~: If this block is selected as the best non-regular expression match, regular expression matching will not take place.
Cheat

Directives: index

Directives: try_files

If a request is made for /blahblah, the first location will initially get the request. It will try to find a file called blahblah in /var/www/main directory. If it cannot find one, it will follow up by searching for a file called blahblah.html.

Directives: rewrite

A request for /rewriteme/hello will be handled initially by the first location block. It will be rewritten to /hello and a location will be searched.

Directives: error_page

Examples

A simple PHP site configuration

Jenkins Cheat Sheet Pdf

App server (Redmine)

Jenkins File Cheat Sheet

App server (Jenkins)