kenorb kenorb - 1 month ago 8
Groovy Question

How to simplify repeated build job syntax?

I've the following Groovy script:

node {
stage('Testing') {
build job: 'Test', parameters: [string(name: 'Name', value: 'Foo'), string(name: 'Param1', value: Param1), string(name: 'Param2', value: Param2), string(name: 'Param3', value: Param3), string(name: 'Param4', value: Param4), string(name: 'Param5', value: Param5)], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Bar'), string(name: 'Param1', value: Param1), string(name: 'Param2', value: Param2), string(name: 'Param3', value: Param3), string(name: 'Param4', value: Param4), string(name: 'Param5', value: Param5)], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Baz'), string(name: 'Param1', value: Param1), string(name: 'Param2', value: Param2), string(name: 'Param3', value: Param3), string(name: 'Param4', value: Param4), string(name: 'Param5', value: Param5)], quietPeriod: 2, wait: false
// ...
}
}


which aims to run multiple parameterized jobs in Jenkins. Since I've huge number of jobs to run with different parameters, I'd like to avoid repeating the same syntax and define parameters once and reuse it.

The first Name parameter is different, but the rest is the same. How can I reuse the same parameters (Param1-Param5) without repeating the same code over and over again?

How this can be achieved?

Answer

You could do that with a simple method :

node {
    stage('Testing') {
        buildJob('Foo')
        buildJob('Bar')
        buildJob('Baz')
        // ...
    }
}

def buildJob(name) {
    build job: 'Test', parameters: [string(name: 'Name', value: name), string(name: 'Param1', value: Param1), string(name: 'Param2', value: Param2), string(name: 'Param3', value: Param3), string(name: 'Param4', value: Param4), string(name: 'Param5', value: Param5)], quietPeriod: 2, wait: false
}
Comments