Override Default Jenkins Pipeline Node Block

4/12/2018

My company has a small pipeline library that we implicitly load for every build. Is there a way to overload the node { block of every build transparently?

My specific case is that I'm provisioning kubernetes slaves with the kubernetes plugin, and I want to provide a default YAML template, while allowing users to pick another template or override specific values. Eg:

node {
  // Gets you a Pod with a DinD engine with a low CPU/Mem request/limit
}

Optionally overridden by name:

node('2-core') {
  // Gets you a Pod with a DinD engine with 2 CPU/ more Mem request/limit
}

Or overridden with a template:

import com.foo.utils.PodTemplates

slaveTemplates = new PodTemplates()

slaveTemplates.bigPod {
  node {
    // Big node
  }
}

Or:

def label = "mypod-${UUID.randomUUID().toString()}"
podTemplate(label: label, yaml: """
apiVersion: v1
kind: Pod
metadata:
  labels:
    some-label: some-label-value
spec:
  containers:
  - name: redis
    image: redis
"""
) {
  node (label) {
    // Same small pod as before PLUS a redis container
  }
}

This seems trickiest, since you want the values of the parent to override the values of the child.

-- pnovotnak
groovy
jenkins
jenkins-pipeline
jenkins-plugins
kubernetes

1 Answer

4/12/2018

You can do this, but, in my opinion, it will lead to confusing behavior and possibly strange error cases.

For example:

echo.groovy

def call(String string) {
  steps.echo "Calling step echo: $string"
}

Jenkinsfile

echo 'hello'

Output:

Calling step echo: hello
  • There is a blog post here that demonstrates this a little more in depth
  • Paid support for some pipeline restriction tools are offered by CloudBees that might solve your use case

The heaviest way to accomplish this is to of course write a plugin.

-- mkobit
Source: StackOverflow