Jenkins Groovy 脚本执行 shell 命令

Jenkins Groovy script to execute shell commands

我正在使用 groovy 脚本来计算构建持续时间并将指标发布到 Hosted Graphite,从命令行执行以下 curl 将产生预期效果:

echo {someMetricHere} | nc carbon.hostedgraphite.com 2003

然而,在我的 groovy 脚本中,生成指标的最后一步是 运行 以下内容:

"echo "+ metric +" | nc carbon.hostedgraphite.com 2003".execute()

返回:

捕获:java.io.IOException:无法 运行 编程“|”:错误=20,不是目录 java.io.IOException: 无法 运行 编程“|”: error=20, 不是目录 在 hudson8814765985646265134.run(hudson8814765985646265134.groovy:27) Caused by: java.io.IOException: error=20, 不是目录 ... 1 个

我假设命令不理解“|”命令的一部分,有什么建议可以将此脚本修复为 运行 预期的 bash?我认为可以在工作区中创建一个 .sh 文件,但不确定如何创建。

想要查看完整脚本的人的 Pastebin:https://pastebin.com/izaXVucF

干杯:)

使用管道 | 试试这个代码:

// this command line definitely works under linux:
def cmd = ['/bin/sh',  '-c',  'echo "12345" | grep "23"']
// this one should work for you:
// def cmd = ['/bin/sh',  '-c',  'echo "${metric}" | nc carbon.hostedgraphite.com 2003']

cmd.execute().with{
    def output = new StringWriter()
    def error = new StringWriter()
    //wait for process ended and catch stderr and stdout.
    it.waitForProcessOutput(output, error)
    //check there is no error
    println "error=$error"
    println "output=$output"
    println "code=${it.exitValue()}"
}

输出:

error=
output=12345
code=0

实现此目的的更简单方法是使用 Jenkins Job DSL。它具有一个 shell 命令,可以从给定的 step 中发出。例如:

// execute echo command
job('example-1') {
    steps {
        shell('echo Hello World!')
    }
}

// read file from workspace
job('example-2') {
    steps {
        shell(readFileFromWorkspace('build.sh'))
    }
}

您可以找到参考 here

我认为你做的串联有问题。

此代码应该有效:

"echo ${metric} | nc carbon.hostedgraphite.com 2003".execute()

如果您必须将变量传递给 groovy 脚本,您可以使用 ${variableName} 来完成。双引号的解释方式与您想象的不同,每个编译器都以一种奇怪的方式对待它。

在您的情况下,以下行应该有助于完成您想要的事情:

sh "echo ${metric} | nc carbon.hostedgraphite.com 2003"