4

I wanted to create a class in /src directory which can access docker and other plugin steps.

So I have a class that looks like this;

class someClassName implements Serializable {
    def env
    def steps
    def docker

    someclassName(env, steps, docker){
        this.step = step
        this.docker = docker
        this.env = env
    }

    def runCommands(String img, List commands){
       docker.image(img).inside {
           commands.each {
             steps.sh it
           }
       }
    }

Now in Jenkinsfile I will have

@Library('name@branch') _
def x = new com.JenkinsLibrary.someClassName(env, steps, docker)
x.runCommands('maven:latest', ['mvn clean', 'mvn test'])

What i dont like is how I have a constructor for each object so that I can call methods that belong to that object. Is there a better object that i can use for my constructor instead of having to use env, steps, docker, etc?

Also, what pipeline steps are available under steps object? same for env?

mkobit
  • 43,979
  • 12
  • 156
  • 150
Z Y .
  • 313
  • 1
  • 3
  • 6

1 Answers1

5

Try sending along the surrounding CPSScript:

class someClassName implements Serializable {
    def script

    someclassName(script){
        this.script = script
    }

    def runCommands(String img, List commands){
        script.docker.image(img).inside {
            commands.each {
                script.sh it
           }
       }
    }
}

and you provide the script by using this in the pipeline script:

@Library('name@branch') _
def x = new com.JenkinsLibrary.someClassName(this)
x.runCommands('maven:latest', ['mvn clean', 'mvn test'])
mkobit
  • 43,979
  • 12
  • 156
  • 150
Jon S
  • 15,846
  • 4
  • 44
  • 45
  • Exactly what I was looking for. To extend on this, is it also possible to use script for all other pipeline steps? Would i be able to use script for most of the objects from pipeline snippet generator? for ex; script.sh, script.httpRequest, script.readJSON in classes under `/src` dir – Z Y . May 05 '18 at 19:49
  • 1
    Yes, that should work... I haven't run into any limitations yet. Just be ware that you can't use the script variable inside methods annotated with `@NonCPS`... – Jon S May 05 '18 at 19:57
  • but it should work on classes that implement Serializable correct? and yes this is great! Thank you so much!!! – Z Y . May 05 '18 at 19:59