How to access pipeline DSL in groovy classes(and not in Jenkinsfile)?

六月ゝ 毕业季﹏ 提交于 2019-12-11 17:52:50

问题


I want to access pipeline steps like 'bat' or 'echo' in my groovy classes but I am not really aware of how the 'script' variable usage works. This is very small repository with only this class and I am calling this class in groovy test(spock test). Can somebody please enlighten me on correct usage of 'script' variable and how the call should look like ?

SoftwareInstallation.groovy

class SoftwareInstallation implements Serializable {
  Script script

def runInstallationJar(repoDir){
    def exitValues=[]
    def configFiles=['software1.xml', 'software2.xml']
    configFiles.each {
        def status = script.bat returnStatus: true, script: " java -jar ${repoDir}\\resources\\software.jar --inputxml=${repoDir}\\resources\\${it}"
        script.echo "Return status : ${status}"
        if (status){
            log 'success'
        }else{
            log 'failure'
        }
        exitValues.add(status)
    }
    return exitValues
}

}

ps- I do have a Jenkinsfile but that just contains a gradle call to run tests.


回答1:


There is an example in the article about Extending with Shared Libraries.

There you'll find following code:

Class

package org.foo
class Utilities implements Serializable {
  def steps
  Utilities(steps) {this.steps = steps}
  def mvn(args) {
    steps.sh "${steps.tool 'Maven'}/bin/mvn -o ${args}"
  }
}

Caller

@Library('utils') import org.foo.Utilities
def utils = new Utilities(this)
node {
  utils.mvn 'clean package'
}

Without shared library

It doesn't really matter whether you defined the class inside of a library or in your script. The approach would be the same:

class Utilities implements Serializable {
  def steps
  Utilities(steps) {this.steps = steps}
  def mvn(args) {
    steps.sh "${steps.tool 'Maven'}/bin/mvn -o ${args}"
  }
}
def utils = new Utilities(this)
node {
  utils.mvn 'clean package'
}


来源:https://stackoverflow.com/questions/51748932/how-to-access-pipeline-dsl-in-groovy-classesand-not-in-jenkinsfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!