在 Jenkins 管道中使用的 groovy 脚本中调用 shell 命令 [英] Calling shell commands in groovy script, used in Jenkins pipeline

查看:186
本文介绍了在 Jenkins 管道中使用的 groovy 脚本中调用 shell 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Jenkins 流水线脚本,其中我加载了一个外部 Groovy 脚本,其中包含一些函数来执行我的构建.这些功能应该是普通的,因为如果有人在某处的本地计算机上运行构建,我也想在 Jenkins 之外使用它们.

I have a Jenkins pipeline script in that I load an external Groovy script that contains some functions to perform my build. These functions should be plain groovy because I also want to use them outside of Jenkins, if someone runs a build on a local computer somewhere.

在这些函数中,我需要执行 shell 命令并评估结果.这在 groovy 调用类似

In these functions I need to execute shell commands and evaluate the result. This works fine in groovy calling a function like

def SomeFunction() {
    def result = "Some shell command".execute().text
}

但是,这种执行方法在管道脚本中不起作用.我不能使用bat/sh",因为这只是管道脚本,我希望我的函数也可以在普通的 groovy 中工作.

However, this method of execution doesn't work in a pipeline script. I can't use "bat/sh" because this is pipeline-script-only, and I want my functions to also work in plain groovy.

我该如何解决这个问题?

How can I work around this?

推荐答案

您不应将 Jenkins Pipeline Groovy 视为常规 Groovy 代码.所有 Pipeline Groovy(截至目前)始终在 Jenkins 主服务器上执行..execute() 永远不会在您期望的地方执行,Jenkins 脚本安全限制会阻止您,以及 Jenkins 上的 CPS 转换 Groovy 引擎都是不期望能够使用完整的 Groovy 语言的原因在管道代码中.

You should not treat Jenkins Pipeline Groovy as regular Groovy code. All Pipeline Groovy (as of right now) is always executed on the Jenkins master. .execute() will never execute where you expect it to, Jenkins script security restrictions will block you, and CPS transformation Groovy engine on Jenkins are all reasons to not expect to be able to use the full Groovy language in pipeline code.

这是来自 Google 网上论坛的相关帖子斯蒂芬·康诺利:

Here is a relevant post from Google Groups by Stephen Connolly:

管道不是常规的.

它是一个建立在 Groovy 之上的 CPS 引擎...它可能看起来像 Groovy,它有时甚至可能像 Groovy 一样走路和嘎嘎叫,但如果你接受它不是,你的生活将会变得无限美好 时髦的.

It is a CPS engine built on top of Groovy... it may look like Groovy, it may even sometimes walk and quack like Groovy, but your life will be infinitely better if you just accept that it is NOT Groovy.

如果您想编写惯用的 Groovy,您可以去全球共享库,即使在那里您也可能遇到问题,除非您真正了解 CPS 的魔力及其全部含义.

Global Shared Libraries is where you go if you want to write idiomatic Groovy, and even there you can hit issues unless you truly understand the CPS magic and its full implications.

使用管道作为最终的编排粘合层,您的生活会轻松很多

Use pipeline as a final orchestration glue layer and your life will be much easier

我建议您阅读整个线程,因为它应该表明您不应将管道代码视为普通的 Groovy 代码.

I recommend you read that entire thread as it should demonstrate that you should not treat the Pipeline code as normal Groovy code.

这篇关于在 Jenkins 管道中使用的 groovy 脚本中调用 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆