Daniel Majano
Daniel Majano

Reputation: 1116

Jenkins: import external package from Jenkinsfile using declarative syntax

I had a groovy code which contains "import groovy.json.JsonSlurper".

I have spent a day testing and I don't know how to load external libraries using declarative syntax.

This is my code:

pipeline {

agent any

import groovy.json.JsonSlurper

        stages {

                stage("test") {

                        steps {
                         }
                }
        }
}

I have read the jenkins documentation, and I have tried to use the next but without success:

@Grab('groovy.json.JsonSlurper') import groovy.json.JsonSlurper

both import and @Grab are not recognized. Some idea?

Thanks!

Upvotes: 4

Views: 3615

Answers (1)

jxramos
jxramos

Reputation: 8266

What @Daniel Majano says is true about the import syntax, but the @Grab syntax I found holds differences of behavior between a Pipeline script maintained directly in Jenkins vs Pipeline script from SCM.

When I placed a Grab command in the Pipeline script for a tester pipeline job I found that it didn't make any difference whether the Grab command was there or if it was commented out.

Pipeline script snippet

However when used from a Pipeline script from SCM it would throw the following exception...

java.lang.RuntimeException: No suitable ClassLoader found for grab

I removed it from the SCM script and everything worked out in the end.


Additional Background

I'm not sure why the grab was choking in the SCM version, but there's definitely some working parts to the groovy editor because if you define a partial grab command it will give you some validation errors pointing to the broken line as you see in the red X box below, with the error The missing attribute "module" is required in @Grab annotations:

groovy Grab syntax validator Therefore the script validator is aware of the Grab annotation as it calls it and that it has both a group and module attribute. I'm using the so called shorthand notation in this example.

Upvotes: 1

Related Questions