【问题标题】:Executing shell commands from inside Pipeline Shared Library从管道共享库内部执行 shell 命令
【发布时间】:2021-12-07 23:18:48
【问题描述】:

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

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

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

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

【问题讨论】:

  • Jenkins 仅从 vars 文件夹加载关键字,因此您需要在 vars 文件夹中创建一个适配器关键字,您可以在其中启动您的类并返回它 - 您可以在 @987654325 中看到这一点following example中的@关键字。

标签: jenkins jenkins-pipeline jenkins-shared-libraries


【解决方案1】:

是的,这是可能的,但并不是一个明显的解决方案。通常在 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() } ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多