How Jenkinsfiles Really Work

I only recently encountered the Jenkinsfile format. Previously I had used the clunky Jenkins UI or the cleaner Circle CI options.

Some of my colleagues had described it as using a special Groovy declarative syntax. It is in fact simply Groovy code using some neat tricks.

Groovy allows a closure (what other languages may call a lambda) to be used as a function parameter:

def block(Closure closure) {

closure.call()

}

This can then be used as follows:

block( { print (‘hello’) } )

Groovy allows the closure to be moved outside the brackets as a code block:

block() {

print ‘hello’

}

Here I have started to use the groovy trick of dropping brackets. In fact you can also drop the leading brackets:

block {

print ‘hello’

}

This is beginning to look like the pipeline or stage steps from a Jenkinsfile.

You can even add parameters:

def wrap(marker, Closure closure{

println marker

closure.call()

println marker

}

// Which can be used as:

wrap (‘name’) {

// something …

}

Jenkinsfiles are code pretending to be config, with the added benefit of being able to become code again when needed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s