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


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


Related Issue(s)



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 { 'echo hello'
def c = new C()

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()


Have more questions?


  • 0
    Markri Please Update


    I tried using the steps variable in my pipeline library (also tried passing the "this" reference), but I can't seem to get it working properly due to some serialization errors. Here's my (redacted) code

    class JobUpdater implements Serializable {

    def updateJenkinsJob(steps){
    jobConfig = "mavenJob('myjob') {\n" +
    " scm {\n" +
    " git {\n" +
    " branch('tags/rc_1')\n" +
    " }\n" +
    " }\n" +
    " triggers {\n" +
    " snapshotDependencies(false)\n" +
    " scm('')\n" +
    " }\n" +

    steps.jobDsl(scriptText: jobConfig)

    And my pipeline script in Jenkins (with or without sandbox tick) is:

    @Library("my-library@feature-jobupdater") import org.mycorp.JobUpdater

    node('linux') {
    release = new JobUpdater()

    For some reason I keep getting following exception

    an exception which occurred:
    Caused: hudson.model.Hudson

    At first I thought it was related to the "jobDsl" step ( using the hudson.model.Hudson class, however when digging into I can't find any reference to that class. So it must be related to the usage of "steps" (in my limited vision on Jenkins)

    If I move the jobDsl() call to the pipeline script with some ugly code crafting, then it seems to be working (although still very annoyingly with script approvals for each update type).

    BTW: Adding the @NonCPS annotation on the updateJenkinsJob doesn't seem to make a difference as well.

    Any clues on this?

Please sign in to leave a comment.