Groovy inside Jenkinsfiles
Where Groovy goes in declarative pipelines
Declarative syntax only allows steps inside steps {}. Arbitrary Groovy goes in a script {} block, or in methods defined below the pipeline {} block, or in a shared library:
pipeline {
agent any
stages {
stage('Version') {
steps {
script {
def sha = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
env.IMAGE_TAG = "${env.BRANCH_NAME}-${sha}" // env.* survives to later stages
}
echo "Tag is ${env.IMAGE_TAG}"
}
}
}
}
Keep script {} blocks small. Large ones are a smell that logic belongs in a shared library step.
Getting data out of shell steps
def out = sh(script: 'kubectl get deploy orders -o jsonpath="{.spec.replicas}"', returnStdout: true).trim()
def code = sh(script: 'curl -fsS http://orders/health', returnStatus: true) // exit code, no failure
if (code != 0) { unstable('health check failed') }
sh 'make test' // returns null; fails the build on non-zero exit
returnStdout includes the trailing newline — always .trim(). Use returnStatus when a non-zero exit is an expected outcome you want to handle.
Built-in globals
| Global | Examples |
|---|---|
env |
env.BUILD_NUMBER, env.BUILD_URL, env.JOB_NAME, env.WORKSPACE, env.BRANCH_NAME, env.CHANGE_ID, env.GIT_COMMIT; set env.X = 'y' (values are strings) |
params |
params.ENV, params.DEPLOY (typed: booleans stay booleans) |
currentBuild |
.result, .currentResult, .number, .displayName, .description, .durationString, .changeSets, .getBuildCauses() |
scm |
The SCM config of the job (checkout scm) |
currentBuild.displayName = "#${env.BUILD_NUMBER} ${env.IMAGE_TAG}"
currentBuild.description = "Deployed to ${params.ENV}"
Files, YAML and JSON
With the Pipeline Utility Steps plugin:
def values = readYaml file: 'deploy/values.yaml'
values.image.tag = env.IMAGE_TAG
writeYaml file: 'deploy/values.yaml', data: values, overwrite: true
def report = readJSON file: 'trivy.json'
def critical = report.Results.collectMany { it.Vulnerabilities ?: [] }.count { it.Severity == 'CRITICAL' }
writeFile file: 'build-info.txt', text: "sha=${env.GIT_COMMIT}\n"
def txt = readFile 'VERSION'
if (fileExists('Makefile')) { sh 'make build' }
These run against the agent's workspace even though the Groovy runs on the controller.
Dynamic parallel stages
def services = ['orders', 'payments', 'catalog']
def branches = services.collectEntries { svc ->
[(svc): {
stage("Test ${svc}") {
dir(svc) { sh 'make test' }
}
}]
}
parallel branches // in declarative, call this inside script {}
Note svc -> — using a named parameter (not a shared loop variable) avoids the classic closure-capture bug where every branch ends up using the last value.
Interpolation traps: secrets and $
withCredentials([string(credentialsId: 'api-token', variable: 'TOKEN')]) {
sh "curl -H 'Authorization: Bearer ${TOKEN}' https://api" // BAD
sh 'curl -H "Authorization: Bearer $TOKEN" https://api' // GOOD
}
With double quotes, Groovy substitutes the secret into the command string before the shell runs — the secret can appear in the process list on the agent, in error messages, and Jenkins prints a warning ("A secret was passed to sh using Groovy String interpolation, which is insecure"). With single quotes, the shell expands $TOKEN from the environment.
When you need both Groovy values and shell variables, escape the shell's $ inside a GString:
sh "docker build -t ${IMAGE}:${TAG} --build-arg USER=\$USER ." // \$USER left for the shell
sh """
for f in \$(ls charts); do helm lint charts/\$f; done
"""
Or pass Groovy values in through the environment and keep the script single-quoted:
withEnv(["IMAGE=${image}", "TAG=${tag}"]) {
sh 'docker build -t "$IMAGE:$TAG" .'
}
load
def helpers = load 'ci/helpers.groovy' evaluates a Groovy file from the workspace (it must end with return this). Useful for repo-local helpers; for anything shared across repos, use a shared library instead.