Calling shell commands in groovy script, used in J

2019-03-05 11:36发布

问题:

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?

回答1:

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.