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

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

问题描述

我有一个Jenkins管道脚本,我加载了一个包含一些函数的外部Groovy脚本来执行我的构建。
这些函数应该是普通的groovy,因为如果有人在某个地方的本地计算机上运行构建,我也想在Jenkins之外使用它们。



在这些函数我需要执行shell命令并评估结果。这在Groovy中调用像

一样的函数可以很好地工作。
$ b $ $ p $ def $ SomeFunction(){
def result =一些shell命令 .execute()。text
}

然而,这种执行方法不起作用在管道脚本中。
我不能使用bat / sh,因为这只是pipeline-script-only,而且我希望我的函数也能用普通的groovy工作。



我该如何解决这个问题?解决方案

您不应该将Jenkins Pipeline Groovy视为常规的Groovy代码。所有Pipeline Groovy(截至目前为止)总是在Jenkins master上执行。 Jenkins脚本安全限制会阻止你,并且CPS转换Jenkins上的Groovy引擎是所有不希望能够实现的原因。 c> .execute()在管道代码中使用完整的Groovy语言。



这是 Stephen Connolly的相关帖子


Pipeline <这是一个建立在Groovy之上的CPS引擎......它可能看起来像Groovy,它有时甚至可能走路和嘎嘎像Groovy一样,但是如果你只是接受它是 NOT Groovy,那么你的生活会变得更好。

Global Shared Libraries是你去的地方if你想编写惯用的Groovy,甚至在那里你可以遇到问题,除非你真正理解CPS的魔力及其全部含义。



使用流水线作为最终的编排胶水层,你的生活将变得更加容易。 您不应该将管道代码视为正常的Groovy代码。


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.

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
}

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?

解决方案

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.

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

Pipeline is NOT 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.

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

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天全站免登陆