Reputation: 37
I am using the pipeline script to build the jobs parallel when parameter matches, but for each parameter it builds upto 10 to 15 jobs parallely, so the code comes around nearly length 450 lines. is that any way to reduce the code or any other way to configure and build the job?
#!/usr/bin/env groovy
pipeline {
agent any
parameters {
choice(
choices: 'Job1\nJob2'\nJob3,
description: '',
name: 'Project'
)
}
stages {
stage ('callJob1') {
when {
expression { params.Project == 'Job1' }
}
steps{
build job: 'test1'
build job: 'test2'
.
.
.
.
.
}
}
stage('callJob2'){
when{
expression { params.Project == 'Job2'}
}
steps{
build job: 'test3'
build job: 'test4'
.
.
.
.
.
}
}
stage('callJob3'){
when{
expression { params.Project == 'Job3'}
}
steps{
build job: 'test5'
build job: 'test6'
.
.
.
.
.
}
}
}
}
Upvotes: 1
Views: 2236
Reputation: 1822
I suggest that you use scripted syntax instead of the declarative one. Scripted versions tend to be more concise and dynamic. While declarative syntax was introduced after the scripted one, it is not necessarily better.
properties([
parameters([
choice(
choices: 'Job1\nJob2'\nJob3,
description: '',
name: 'Project'
)
])
])
stage('callJob1') {
if (params.Project == 'Job1') {
build job: 'test1'
build job: 'test2'
}
}
stage('callJob2') {
if (params.Project == 'Job2') {
build job: 'test3'
build job: 'test4'
}
}
Not to mention, you can do a lot of neat tricks thanks to the scripted nature (which you can't normally do in declarative mode). For example "generating" stages dynamically or setting job properties dynamically: while in declarative mode you can't pre-calculate and then pass job parameters
, here you can pass elements in form or a regular List to properties
(for example: set of parameters depend on the name of the branch)
Also no repetitive boilerplate blocks of agent, when, expression etc. IMO scripted syntax is far easier if you are familiar with programming and would like to take maximum benefit that code can provide to you.
Upvotes: 0
Reputation: 1051
Try extract common parts in steps and define methods in the jenkinsfile. Methods defined in jenkinsfile A can also be called in jenkinsfile B in same project.
ex:
def func() {
}
.
.
stages {
stage('Job1'){
steps {
script {
func()
}
}
}
stage('Job2'){
steps {
script {
func()
}
}
}
}
Upvotes: 1