从管道共享库中执行 shell 命令
Executing shell commands from inside Pipeline Shared Library
我正在编写一个将在管道中使用的共享库。
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 中,我导入库,调用 class 并在 script
部分内执行部署函数:
stage('mystep') {
steps {
script {
def deployer = com.mypackage.HelmDeployer("test")
deployer.deploy()
}
}
}
但是,控制台日志上未打印任何输出或错误。
是否可以在共享库中执行内容 class?如果是这样,我做错了什么?
是的,这是可能的,但不是一个明显的解决方案。通常在 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() } ...
我正在编写一个将在管道中使用的共享库。
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 中,我导入库,调用 class 并在 script
部分内执行部署函数:
stage('mystep') {
steps {
script {
def deployer = com.mypackage.HelmDeployer("test")
deployer.deploy()
}
}
}
但是,控制台日志上未打印任何输出或错误。
是否可以在共享库中执行内容 class?如果是这样,我做错了什么?
是的,这是可能的,但不是一个明显的解决方案。通常在 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() } ...