4

I have written a groovy script to collect some statistics from my Jenkins server, which works ok in the default case. However, when I want to pass options to it, I am getting trouble:

(1) The standard groovy CliBuilder exists, but fails to instantiate under jenkins-cli:

import jenkins.model.*
import groovy.util.CliBuilder
println("CliBuilder imported; calling constructor...")
def cli = new CliBuilder(usage: 'myscript.groovy [-halr] [name]')

results in

$ java -jar "jenkins-cli.jar" -s https://myjenkins1/ groovy myscript.groovy
CliBuilder imported; calling constructor...

ERROR: Unexpected exception occurred while performing groovy command.
java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:195)
    at RemoteClass.class$(RemoteClass)
    at RemoteClass.$get$$class$groovy$util$CliBuilder(RemoteClass)
    at RemoteClass.run(RemoteClass:4)
    at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:266)
....

(2) the options starting with a dash are intercepted by jenkins-cli, instead of passing it to the script

$ java -jar "jenkins-cli.jar" -s https://myjenkins/ groovy ./myscript.groovy -h
ERROR: "-h" is not a valid option
java -jar jenkins-cli.jar groovy [SCRIPT] [ARGUMENTS ...] [--username VAL] [--password VAL] [--password-file VAL]
Executes the specified Groovy script.
 SCRIPT              : Script to be executed. File, URL or '=' to represent
                       stdin.
 ARGUMENTS           : Command line arguments to pass into script.
 --username VAL      : User name to authenticate yourself to Jenkins
 --password VAL      : Password for authentication. Note that passing a
                       password in arguments is insecure.
 --password-file VAL : File that contains the password

Does it mean that the jenkins-cli groovy interface is meant only for simple tasks and should not handle complicated command lines? Or are these known caveats with known workarounds?

jmster
  • 943
  • 1
  • 12
  • 25

1 Answers1

0

A few issues here:

  1. The jenkins-cli.jar requires groovy to be piped in via stdin.
  2. Command line arguments are read via the args array
  3. It does appear that args with a - are passed to the local jenkins-cli.jar and not the groovy script running on the server.

So given the following groovy script saved as cli.groovy:

println(args)

You would run it like this:

$ java -jar "jenkins-cli.jar" -s https://myjenkins/ groovy = foo bar baz bat < myscript.groovy

Which prints:

[foo, bar, baz, bat]
gkfasdfasdf
  • 1
  • 1
  • 1