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

Issue

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

Environment

Related Issue(s)

JENKINS-33353

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)

References

Have more questions?

1 Comments

  • 0
    Avatar
    Markri Please Update

    Hi,

    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()
    release.updateJenkinsJob(steps)
    }

    For some reason I keep getting following exception

    an exception which occurred:
    ....
    Caused: java.io.NotSerializableException: hudson.model.Hudson

    At first I thought it was related to the "jobDsl" step (https://www.jenkins.io/doc/pipeline/steps/job-dsl/) using the hudson.model.Hudson class, however when digging into https://github.com/jenkinsci/job-dsl-plugin 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.