Friday, June 5, 2020

using load in Jenkins Pipeline with multiple instances

The proper solution is likely to use Shared Library.  But I don't have it setup and don't wanted to set that up just for a few functions.

OK, now we get that out of the way, let's look at the following example

fun = load scripts/fun.groovy
fun.play
and in fun.groovy, we have

def play() {
  sh "echo play"
}

return this
now if we want to add a variable so we can have different kind of "fun"

def type
def play() {
  sh "echo playing $type"
}
def setType(string _type) {
  type = _type
}
return this
i was hoping i can load "fun.groovy" twice,



fun = load scripts/fun.groovy
fun.setType('basketball')
more_fun = load scripts/fun.groovy
more_fun.setType('ping pong')
fun.play
more_fun.play
i ended up getting

play ping pong
play ping pong
apparently there's only one instance loaded.  to get around that, i then try

class FUN {
  def type
  def dsl
  def play() {
     dsl.sh "echo play $type"
  }
  FUN(_dsl, string _type) {
    type = _type
    dsl = _dsl
  }
}
def getFun(dsl,type) {
  return new FUN(dsl,type)
}
return this
so we can now do this

fun = load scripts/fun.groovy
basketball = fun.getFun(this,'basketball')
pingpong = fun.getFun(this,'ping pong')
basketball.play
pingpong.play
 now we'll get

play basketball
play ping pong
note that i've pass in "this" from the pipeline to the FUN class.  The reason is the FUN class is no longer in the pipeline scope.  To use any features/functions from the pipeline, we'll have to reference the pipeline object.