简体   繁体   English

在詹金斯管道中使用的Groovy脚本中调用Shell命令

[英]Calling shell commands in groovy script, used in Jenkins pipeline

I have a Jenkins pipeline script in that I load an external Groovy script that contains some functions to perform my build. 我有一个Jenkins管道脚本,我加载了一个外部Groovy脚本,其中包含一些执行我的构建的功能。 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. 这些功能应该很简单,因为如果有人在本地计算机上运行构建,我也想在Jenkins之外使用它们。

In these functions I need to execute shell commands and evaluate the result. 在这些函数中,我需要执行shell命令并评估结果。 This works fine in groovy calling a function like 这在groovy调用类似

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. 我不能使用“ bat / sh”,因为这仅是管道脚本,并且我希望我的函数也能以普通的方式工作。

How can I work around this? 我该如何解决?

You should not treat Jenkins Pipeline Groovy as regular Groovy code. 您不应将Jenkins Pipeline Groovy视为常规的Groovy代码。 All Pipeline Groovy (as of right now) is always executed on the Jenkins master. 所有Pipeline Groovy(截至目前)始终在Jenkins主服务器上执行。 .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. .execute()永远不会在您期望的位置执行,Jenkins脚本安全性限制将阻止您,并且Jenkins上的CPS转换Groovy引擎都是无法在管道代码中使用完整Groovy语言的原因。

Here is a relevant post from Google Groups by Stephen Connolly: 这是斯蒂芬·康诺利(Stephen Connolly)的Google网上论坛相关文章

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. 它是在Groovy之上构建的CPS引擎...它看起来像Groovy,甚至有时像Groovy一样走路和嘎嘎作响,但是如果您仅接受它不是 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. 如果您想编写惯用的Groovy,可以使用Global Shared Libraries,甚至在那里也可能遇到问题,除非您真正了解CPS的魔力及其全部含义。

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. 我建议您阅读整个线程,因为它应该表明您不应将管道代码视为普通的Groovy代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM