Groovy for pipelines · Lesson 3 of 8 · 3 min read
Control flow, methods, classes and errors
Conditions and loops
if (env.BRANCH_NAME == 'main') { ... } else if (env.CHANGE_ID) { ... } else { ... }
switch (params.ENV) { // Groovy switch matches lists, ranges, regex, classes
case 'prod': replicas = 6; break
case ['staging', 'qa']: replicas = 2; break
case ~/feature-.*/: replicas = 1; break
default: replicas = 1
}
for (svc in services) { echo svc } // classic loop — CPS-safe
for (int i = 0; i < services.size(); i++) { ... }
while (attempt < 5) { ... }
Methods
def imageTag(String sha, String branch = 'main') { // default parameter
return branch == 'main' ? sha.take(7) : "${branch}-${sha.take(7)}"
}
def deploy(Map args) { // named arguments arrive as a Map
echo "Deploying ${args.service} v${args.version ?: 'latest'}"
}
deploy(service: 'orders', version: '1.4.2')
The last expression is returned implicitly, but writing return is clearer.
Classes
package org.acme.ci
class ImageRef implements Serializable {
String registry
String repo
String tag
String toString() { "${registry}/${repo}:${tag}" }
}
Classes in shared libraries should implement Serializable (pipelines checkpoint their state to disk). Groovy also has traits, properties with automatic getters/setters, and @Field (to declare script-level fields in a vars/ file).
Exceptions
try {
sh 'make integration-test'
} catch (err) {
echo "Integration tests failed: ${err}"
currentBuild.result = 'UNSTABLE'
} finally {
junit 'reports/**/*.xml'
}
error 'Missing IMAGE_TAG' // pipeline step: fail the build with a message
unstable 'Coverage below 80%' // mark UNSTABLE and continue
Catching everything can swallow aborts — when a user clicks Abort or a timeout fires, Jenkins throws FlowInterruptedException. Re-throw it (or catch narrower exceptions), otherwise aborted builds keep running. catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { ... } is the declarative-friendly alternative.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.