Contents
- 1 Groovy scripting for Jenkins
- 1.1 Template for utility classes
- 1.2 Template for entity classes
- 1.3 Enum definition
- 1.4 Wait for some time
- 1.5 Check if a file exists
- 1.6 Run a Bash command
- 1.7 Change the build number to a string
- 1.8 Split a string
- 1.9 Create a string concatenating values
- 1.10 Concatenate a long string
- 1.11 Do a curl to an API
- 1.12 Convert a JSON text to object
- 1.13 Write text to a file
- 1.14 Null or empty check
- 1.15 Iterate over a list
- 1.16 Iterate over map
- 1.17 Error management
- 1.18 Get the version of a Jenkins plugin
- 1.19 Get all the Git repos used by pipelines
- 1.20 Generate a datetime timestamp
- 1.21 Convert a date to timestamp
- 2 Pipeline library creation
- 2.1 Folder structure
- 2.2 Change to a Jenkins job folder and perform actions on it
- 2.3 Run a Bash command
- 2.4 Compress a folder into zip
- 2.5 Credentials usage
- 2.6 Method that receives a fixed set of parameters and uses them as credentials
- 2.7 Method that receives an object and optional parameters
- 2.8 Dynamic stages
- 2.9 Publish a generated html in Jenkins
- 3 Jenkins management
Groovy scripting for Jenkins
Template for utility classes
package REPLACE_PACKAGE_NAME_JAVA_STYLE class REPLACE_CLASS_NAME { private steps REPLACE_CLASS_NAME(steps) { this.steps = steps } def REPLACE_METHOD_NAME(REPLACE_PARAMS){...} }
Template for entity classes
package REPLACE_PACKAGE_NAME_JAVA_STYLE class REPLACE_CLASS_NAME { String REPLACE_STRING_FIELD boolean REPLACE_BOOLEAN_FIELD int REPLACE_INT_FIELD ... }
Enum definition
enum REPLACE_ENUM_NAME { REPLACE_VALUE_1, REPLACE_VALUE_2, ... }
Wait for some time
We can use SECONDS, MINUTES, HOURS…
sleep(time:3, unit:"MINUTES")
Check if a file exists
steps.fileExists(REPLACE_FILE_PATH)
Run a Bash command
steps.sh "REPLACE_COMMAND"
result = steps.sh(script: "REPLACE_COMMAND", returnStdout: true).trim()
Change the build number to a string
steps.currentBuild.displayName = REPLACE_TEXT
Split a string
def results = inputString.split("REPLACE_SEPARATOR")
def results = inputString.tokenize("REPLACE_SEPARATOR")
Create a string concatenating values
"${VALUE_1} ${VALUE_2} ...".toString()
Concatenate a long string
StringBuffer buffer = new StringBuffer() for (it in REPLACE) { buffer<<"REPLACE" } result = buffer.toString()
Do a curl to an API
def results = steps.sh(script: "curl -k -S -s -H \"Content-Type: application/json\" -H \"Authorization: Basic REPLACE_TOKEN\" -X GET REPLACE_URL" , returnStdout: true)
Convert a JSON text to object
def result = steps.readJSON(text: REPLACE_TEXT, returnStdout: true).trim())
def result = return new JsonSlurper().parseText(REPLACE_TEXT)
Write text to a file
steps.writeFile file: REPLACE_FILE_PATH, text: REPLACE_TEXT_CONTENT
Null or empty check
if (var == null || var.isEmpty()) {...}
Iterate over a list
objects.each({object -> {...}})
Iterate over map
map.each({keyName, value -> {...}})
Error management
if(REPLACE_CONDITION){ ... }else { throw new Exception("Replace error message") } ... try { // Do normal actions steps.echo "Success" } catch(e) { // steps.echo "Error: ${e}" // steps.unstable("REPLACE_WARNING_MESSAGE") // steps.error "REPLACE_ERROR_MESSAGE" } finally { // Replace what to do for both success and error cases, e.g. close a connection }
Get the version of a Jenkins plugin
def version = Jenkins.instance.pluginManager.getPlugin("REPLACE_PLUGIN_NAME").getVersion()
Get all the Git repos used by pipelines
Jenkins.instance.getAllItems(Job.class).each { for (scm in it.SCMs) { if (scm instanceof hudson.plugins.git.GitSCM) { scm.getRepositories().each { it.getURIs().each { def gitUrl = it.toString() } } } } }
Generate a datetime timestamp
def dateFormatter = new SimpleDateFormat("dd-MM-yyyy__HH-mm-ss") def timestamp = dateFormatter.format(new Date())
Convert a date to timestamp
def dateToTimestamp(Date date) { def longTimestamp = null if (date!=null) { longTimestamp = date.getTime() } return longTimestamp }
Pipeline library creation
Folder structure
- docs: any documentation apart from README.md file
- resources: configs, scripts…
- src: Groovy running code
- test: Groovy testing code
- vars: Groovy methods that will be called from pipelines
Change to a Jenkins job folder and perform actions on it
dir("../../jobs/" + REPLACE_PIPELINE_NAME + "/jobs/" + "REPLACE_PATH") { // Perform actions }
Run a Bash command
sh "REPLACE_COMMAND || true"
Compress a folder into zip
zip zipFile: "REPLACE_FILE_NAME", dir: "REPLACE_FOLDER_TO_COMPRESS"
Credentials usage
stage("REPLACE_STAGE_NAME") { script { withCredentials([string(credentialsId: 'CREDENTIAL_ID_1', variable: 'VARIABLE_CONTAINING_VALUE_1'),...]) {...} } }
Method that receives a fixed set of parameters and uses them as credentials
def call(String PARAM_1, String PARAM_2, ...) {...}
Method that receives an object and optional parameters
import REPLACE_GROOVY_CLASS_PATH_LIKE_JAVA_IMPORT def call(model, Map params = [:]) { // Call static method REPLACE_CLASS.REPLACE_METHOD(REPLACE_PARAMS) ... // Call method using object def object = new REPLACE_CLASS(this, REPLACE_PARAMS) object.REPLACE_METHOD(REPLACE_PARAMS) // In case of error, e.g. missing required params error('REPLACE_ERROR_TEXT') }
Dynamic stages
node(REPLACE_NODE_LABEL) { stage('REPLACE_STAGE_1') { ... sshagent([REPLACE_AGENT]) { dir ("REPLACE_FOLDER") { REPLACE_ACTIONS_TO_DO_IN_FOLDER } } } stage('REPLACE_STAGE_2'){...} ... }
Publish a generated html in Jenkins
stage("REPLACE_STAGE_NAME") { script { publishHTML (target: [ allowMissing: false, alwaysLinkToLastBuild: false, keepAll: true, reportDir: 'REPLACE_FOLDER_WHERE_FILE_IS_GENERATED', reportFiles: 'REPLACE_NAME_MAIN_HTML_FILE', reportName: 'REPLACE_DISPLAY_NAME_JENKINS' ]) } }
Jenkins management
Get the values of the credentials in Jenkins
Run in Manage Jenkins –> Script console
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials( com.cloudbees.plugins.credentials.common.StandardCredentials.class, Jenkins.instance, null,null) for (c in creds) { println c.class if (c.properties.privateKeySource) { println( "ID: " + c.id + ", UserName: " + c.username + ", Private Key: " + c.getPrivateKey() + "\n") } else if (c.properties.password) { println( "ID: " + c.id + ", UserName: " + c.username + ", Password: " + c.password + "\n") } else if (c.properties.secret) { println ( "ID: " + c.id + "secret: " + c.secret + "\n") } }