In Jenkins pipeline how can I get the return from method to use in next stage?

1k views Asked by At
node() {
    stage("health check function"){
        def (healthcheck) = withCredentials([string(credentialsId: 'HTTP_TOKEN', variable: 'HTTP_TOKEN')]){
                            def health_check = sh returnStdout:true, script:"""
                            #some of the script content will go here before calling the curl
                            health_check_code=\$(curl http://$URL)
                            """
                            return "${health_check_code}"
        }
    }
    stage("funcreturn"){
        def status = healthcheck()
    }
}

I want to get the status code from health check function stage using the healthcheck method so I can call this method in further stage of pipeline to get the current status code . But in Jenkins I am getting following error java.lang.StringIndexOutOfBoundsException: String index out of range: 1. Is it possible to get the value from method here ?

1

There are 1 answers

0
smelm On

The main problem of the code is that stages have their own scope (because { ... } is a closure). That's why healthcheck can't be found in the later stage because it is basically a local variable in a function.

One way to work around this is to make it a global variable by omitting the def in the declaration:

withCredentials(){
    
    // some commands

    healthcheck = healthcheck_code // no def used to declare variable
                                   // this is a global variable
}

The other solution would be to (which is an lesser known fact) return from the first stage.

If you return a value from a stage, it can be assigned to a variable (at least in scripted pipelines, I don't know about declarative). If there is no explicit return the last expression will be returned. It should be possible to return from the withCredentials step as well (haven't tried it for myself yet)

def healthcheck = stage("health check function"){
    withCredentials([string(credentialsId: 'HTTP_TOKEN', variable: 'HTTP_TOKEN')]){
                        def health_check = sh returnStdout:true, script:"""
                        #some of the script content will go here before calling the curl
                        health_check_code=\$(curl http://$URL)
                        """
                        return "${health_check_code}"
    }
}

// use healthcheck here

I am not sure how your healthcheck variable should be callable. Is that a groovy feature I am not aware of? My guess is that if (for whatever reason) you want to make it a function returning the value instead of the value itself, you need to enclose it in {} making it a anonymous function.

I cannot figure out, why you are getting the string out of range error, but I am pretty sure it happens outside of your code snippet.