从管道共享库内部执行shell命令



我正在编写一个将在管道中使用的共享库。

class Deployer implements Serializable {
def steps
Deployer(steps) {
this.steps = steps
}

def deploy(env) {
// convert environment from steps to list
def process = "ls -l".execute(envlist, null)
process.consumeProcessOutput(output, error)
process.waitFor()
println output
println error
}
}

在Jenkinsfile中,我导入库,调用类,并在script部分中执行部署函数:

stage('mystep') {
steps {
script {
def deployer = com.mypackage.HelmDeployer("test")
deployer.deploy()
}
}
}

但是,控制台日志上不会打印任何输出或错误。

是否可以在共享库类中执行内容?如果是,我怎么做错了,做错了什么?

是的,这是可能的,但不是一个明显的解决方案。通常在Jenkinsfile中完成但移动到共享库的每个调用都需要引用您传递的steps对象。

您也可以通过调用steps.env来引用Jenkins环境。

我给你举一个简短的例子:

class Deployer implements Serializable {
def steps
Deployer(steps) {
this.steps = steps
}
def callMe() {
// Always call the steps object
steps.echo("Test")
steps.echo("${steps.env.BRANCH_NAME}")
steps.sh("ls -al")
// Your command could look something like this:
// def process = steps.sh(script: "ls -l", returnStdout: true).execute(steps.env, null)
...
}
}

您还必须导入共享库的对象并创建它的实例。在管道之外定义以下内容。

import com.mypackage.Deployer // path is relative to your src/ folder of the shared library
def deployer = new Deployer(this) // 'this' references to the step object of the Jenkins

然后你可以在你的管道中这样称呼它:

... script { deployer.test() } ...

最新更新