Scripted Pipeline and Groovy for Jenkins: node, script Blocks, Functions, try/catch and Error Handling
Scripted Pipeline Basics
groovy
ode('linux') {
try {
stage('Checkout') {
checkout scm
}
stage('Build') {
sh 'mvn -B package'
}
stage('Test') {
sh 'mvn -B test'
}
currentBuild.result = 'SUCCESS'
} catch (err) {
currentBuild.result = 'FAILURE'
echo "Build failed: ${err}"
throw err // re-throw so Jenkins marks the build red
} finally {
junit allowEmptyResults: true, testResults: 'target/surefire-reports/*.xml'
cleanWs()
}
}
- No fixed structure: any Groovy is allowed
node('label') { }allocates an agent and a workspace. Withoutnode, steps run on the controller in a light way (flyweight), which is fine forechobut not for builds- More flexible, but easier to write messy or insecure code. Prefer declarative with small
scriptblocks
Groovy in 10 Minutes
groovy
// variables
def name = 'shop'
int count = 3
def items = ['api', 'web', 'db'] // list
def config = [env: 'prod', replicas: 3] // map
// string interpolation: only in double quotes
echo "Deploying ${name} to ${config.env} with ${config.replicas} replicas"
// conditionals
if (config.env == 'prod') {
echo 'careful'
} else if (config.env == 'staging') {
echo 'ok'
}
// loops
for (item in items) { echo item }
items.each { i -> echo "item ${i}" }
(1..3).each { n -> echo "n=${n}" }
config.each { k, v -> echo "${k}=${v}" }
// functions
def greet(String who, String greeting = 'Hello') {
return "${greeting}, ${who}"
}
echo greet('Jenkins')
// ternary, elvis, safe navigation
def label = count > 2 ? 'many' : 'few'
def region = params.REGION ?: 'us-east-1'
def len = config.missing?.size()
script Inside Declarative
groovy
pipeline {
agent any
stages {
stage('Compute') {
steps {
script {
def version = sh(script: 'cat VERSION', returnStdout: true).trim()
def code = sh(script: './check.sh', returnStatus: true) // exit code, does not fail
env.APP_VERSION = version
if (code != 0) {
unstable('check.sh reported warnings') // mark build yellow
}
echo "Version ${version}"
}
}
}
stage('Use it') {
steps { sh 'echo $APP_VERSION' }
}
}
}
| Step option | Effect |
|---|---|
sh(script: '...', returnStdout: true) | Returns the command output as text (trim it!) |
sh(script: '...', returnStatus: true) | Returns the exit code and does not fail the step |
unstable('message') | Marks the build UNSTABLE |
error('message') | Stops with FAILURE and a message |
currentBuild.result = 'UNSTABLE' | Set the result manually |
Error Handling
groovy
// 1) try/catch: handle and continue
stage('Optional lint') {
steps {
script {
try {
sh 'npm run lint'
} catch (e) {
echo "Lint failed but we continue: ${e.message}"
currentBuild.result = 'UNSTABLE'
}
}
}
}
// 2) catchError: mark the stage and the build, but keep going
stage('Docs') {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE', message: 'docs failed') {
sh 'make docs'
}
}
}
// 3) retry and timeout together
retry(3) {
timeout(time: 2, unit: 'MINUTES') {
sh './flaky-integration.sh'
}
}
// 4) warnError
warnError('tests failed') { sh 'make test' }
Parsing Data
groovy
script {
def info = readJSON file: 'package.json' // pipeline-utility-steps plugin
echo "App ${info.name} version ${info.version}"
def yaml = readYaml file: 'config.yaml'
writeJSON file: 'out.json', json: [build: env.BUILD_NUMBER, result: 'ok'], pretty: 4
def txt = readFile 'notes.txt'
writeFile file: 'hello.txt', text: "built ${env.BUILD_NUMBER}"
}
Pitfalls: CPS and Serialization
Pipeline code runs in a special engine (CPS) so that builds can survive a Jenkins restart. This brings some rules.
- Some Java and Groovy objects cannot be saved between steps. Keeping a non-serializable object (for example a
Matcher,JsonSlurperresult or an iterator) in a variable across a pipeline step causesNotSerializableException - Solution: use the pipeline steps (
readJSON) or put heavy Groovy in a method marked@NonCPSthat returns simple data (strings, lists, maps) - Code in
@NonCPSmethods must not call pipeline steps such asshorecho .eachclosures work, but older Groovy versions have limits with some collection methods in CPS. When in doubt use a classicforloop- Keep Groovy logic small. Complex logic belongs in a script file (
sh './build.sh') or a shared library with tests
groovy
@NonCPS
def parseVersions(String text) {
def result = []
def m = text =~ /(\d+\.\d+\.\d+)/
while (m.find()) { result << m.group(1) }
return result // simple list of strings: safe to keep
}
Sandbox and Script Approval
- Pipelines run in a Groovy sandbox that allows only approved methods. If a method is blocked you get *Scripts not permitted*
- An administrator can approve the signature in *Manage Jenkins, In-process Script Approval*, but approve only what is safe
- Shared libraries from trusted repositories can run outside the sandbox (see the shared library lesson)
- Never approve generic methods like
Runtime.execor anything that reads files or environment variables of the controller
Practice Tasks
- Rewrite a small declarative pipeline as a scripted one and compare
- Write a function that returns a version string, and use it in two stages
- Add
try/catch/finallythat always archives logs and re-throws the error - Use
returnStatusto run a check and mark the build UNSTABLE when it returns 2 - Cause and fix a
NotSerializableExceptionwith@NonCPS
Conclusion
Scripted pipelines and script blocks give the full power of Groovy. Learn variables, lists, maps, loops and functions, handle errors with try/catch, catchError, retry and timeout, parse data with readJSON, and avoid CPS serialization pitfalls by keeping Groovy small and using @NonCPS for pure data work.
Quick Summary: scripted node/stage; Groovy basics; script block; returnStdout/Status; unstable/error; catchError/warnError/retry/timeout; readJSON/readYaml; CPS + @NonCPS; sandbox.

