Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

groovy - 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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}"
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...