João Amaro
João Amaro

Reputation: 496

Passing variables inside jenkins pipeline closure body

I have created a pipeline function to retry stages 3 times:

def restart(body){
    retry(3){
        body()
    }
}

And I'm calling it like this:

def prepareStage(accountName, slave_tag) {
    return {
        restart(){
            node(slave_tag){
                stage("${target} ${accountName}") {
                    build job: "pipelines/${accountName}/${env.BRANCH_NAME}"
                }
            }
        }
    }
}

It works fine, but now I wanted to pass another variable "retries" to decide whether it should retry 3 times or not, something like this:

def restart(body, retries){
    if (retries == false){
        body()
    }
    else {
        retry(3){
            body()
        }
    }
}

def prepareStage(accountName, slave_tag, retries) {
    return {
        restart(retries){
            node(slave_tag){
                stage("${target} ${accountName}") {
                    build job: "pipelines/${accountName}/${env.BRANCH_NAME}"
                }
            }
        }
    }
}

But I keep getting "no such DSL method restart"

Upvotes: 1

Views: 1431

Answers (1)

João Amaro
João Amaro

Reputation: 496

It's solved thanks to @Vasiliki Siakka comment:

def restart(retries, body){
    if (retries == false){
        body()
    }
    else {
        retry(3){
            body()
        }
    }
}

def prepareStage(accountName, slave_tag, retries) {
    return {
        restart(retries){
            node(slave_tag){
                stage("${target} ${accountName}") {
                    build job: "pipelines/${accountName}/${env.BRANCH_NAME}"
                }
            }
        }
    }
}

Upvotes: 1

Related Questions