Making HTTPS calls in a pure Groovy shared lib for Jenkins pipeline

Demonic version of the Jenkins logo

Recently I lost a lot of time on this. Hence I want to share a working solution, even if i cannot take the time to detail the issue.

I'm taking about writing reusable code for Jenkinsfiles :

One cannot simply use Groovy HTTPBuilder, because of Jenkins 2 custom Groovy interpreter that follow the Continuation Passing Style paradigm :

Hence the solution is to invoke the http_request plugin :

def jenkinsHttpGet(Map args) {
    def response = args.jenkinsWorkflowScript.invokeMethod 'httpRequest', [[args.url: url]] as Object[]
    if (response.status != 200) {
        jenkinsWorkflowScript.invokeMethod 'echo', [response.content] as Object[]
        throw new HttpResponseException(response.status, 'HTTP error')

This function can be used like this in a Jenkinsfile :

jenkinsHttpGet jenkinsWorkflowScript:this, url:''

The invokeMethod trick makes it possible to invoke builtin functions from classes defined in shared libs.

Beware ! This code can trigger a java.lang.RuntimeException: Could not generate DH keypair if you are using Java 7. Upgrading to an 1.8 JVM for Jenkins fixed the issue.

You'll also have to take good care to make all your Groovy classes Serializable.

At Voyages-Sncf, we are in the process of building a Groovy library of common tools that can be used both in CLI and in Jenkinsfiles.