Groovy and Jenkins cheat sheet

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")
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>