Opscraft
Groovy for pipelines · Lesson 2 of 8 · 4 min read

Collections and closures

Lists and maps

def services = ['web', 'api', 'worker']
services << 'cron'                    // append
services.size()
services[0]; services[-1]             // first, last
services.contains('api')
services.unique(); services.sort(); services.reverse()
services.join(',')                    // "web,api,worker,cron"

def cfg = [env: 'prod', replicas: 3]
cfg.env                                // 'prod'
cfg['replicas']
cfg.region = 'ap-south-1'              // add
cfg.containsKey('env')
cfg.get('timeout', 300)                // default if missing (also inserts it!)
cfg.getOrDefault('timeout', 300)       // default without inserting
cfg.each { k, v -> echo "${k}=${v}" }
def merged = defaults + overrides      // map merge — right side wins

Map keys in [env: 'prod'] are strings ('env'); to use a variable's value as a key write [(keyVar): value].

Closures

A closure is a block of code you can pass around — an anonymous function:

def twice = { x -> x * 2 }
twice(4)                                // 8
def greet = { "Hello ${it}" }           // 'it' is the implicit single parameter
def add = { a, b -> a + b }

Pipeline steps take closures as their last argument, which is why the syntax looks like blocks:

dir('api') { sh 'make test' }                       // dir(path, closure)
withCredentials([...]) { sh 'deploy.sh' }
timeout(time: 10, unit: 'MINUTES') { input 'OK?' }
Enlarge diagramdir('api')a step{ sh 'make test' }a closure: code to run inside that directorydir('api') { sh 'make test' } is the same as dir('api', { sh 'make test' })
Figure 1. A closure is a block of code passed as the last argument. That is why pipeline steps look like blocks.
Swipe sideways to see all of it, or tap to open it full screen.

The collection methods you'll use

Method Does Example
each Iterate services.each { echo it }
eachWithIndex Iterate with index list.eachWithIndex { s, i -> ... }
collect Transform (map) services.collect { "${it}-svc" }
findAll Filter services.findAll { it.startsWith('w') }
find First match nodes.find { it.ready }
any / every Some / all match results.every { it == 'SUCCESS' }
inject Reduce nums.inject(0) { sum, n -> sum + n }
groupBy Group into a map pods.groupBy { it.namespace }
collectEntries Build a map services.collectEntries { [(it): "stage-${it}"] }
sum, max, min, count Aggregates sizes.sum()

collectEntries is the standard trick for building dynamic parallel branches (see the pipeline lesson).

Delegates and DSLs (why Jenkins syntax looks the way it does)

Closures have a delegate — an object that method calls inside the closure are resolved against. Jenkins' declarative syntax, Job DSL and Gradle all use this: inside pipeline { stages { ... } } the calls stage, steps are resolved by the delegate object. You can build the same pattern in a shared library:

// vars/deployConfig.groovy
def call(Closure body) {
  def cfg = [:]
  body.resolveStrategy = Closure.DELEGATE_FIRST
  body.delegate = cfg
  body()
  echo "Deploying ${cfg.service} to ${cfg.target}"
}
// Jenkinsfile
deployConfig {
  service = 'orders'
  target = 'staging'
}
Enlarge diagramJenkinsfiledeployConfig { service ='orders'; target = 'staging' }delegate = cfgassignments go to themapcfg[service: orders,target: staging]
Figure 2. Why Jenkins syntax reads like configuration: the closure's delegate is an object, so service = 'orders' sets a field on it.
Swipe sideways to see all of it, or tap to open it full screen.