How do I access Pipeline DSLs from inside a Groovy class

Issue

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

Environment

  • CloudBees Jenkins Enterprise
  • Jenkins

Related Issue(s)

[JENKINS-33353]

Resolution

In the main Pipeline script, as well as scripts it loads and 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)
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.