How do I access Pipeline DSLs from inside a Groovy class?

Article ID:217736618
1 minute readKnowledge base

Issue

I would like to access Pipeline DSL from a groovy class.

Resolution

In the main Pipeline script, as well as scripts it loads, scripts in vars/*.groovy and the implicit outer scope of scripts in src/**/*.groovy, implicit global variables such as env are bound by default, the steps variable can be used to access Pipeline steps, and functions not otherwise defined are passed along to steps.

steps variable

class C implements Serializable {
 def stuff(steps) {
   steps.node {
     steps.sh 'echo hello'
   }
 }
}
def c = new C()
c.stuff(steps)

But inside an explicit type definitions, the implicit script scope is not available, so anything needed must be passed in somehow—​steps in the above case, so you can also use the more general example described below where the whole Script is being passed in.

script variable

class C implements Serializable {
  def stuff(script) {
    script.node {
      script.echo "running in ${script.env.JENKINS_URL}"
    }
  }
}
def c = new C()
c.stuff(this)