Issue
Is there way in job dsl to configure postBuildSteps only if build succeeds, for a maven job. I saw there is postSuccessfulBuildSteps which applies only to release job.
Solution
You have to use a "configure" block to append "custom" <runPostStepsIfResult>
settings into the config.xml
This works for me:
job(type: Maven) {
name('MyMavenJob')
goals('install')
preBuildSteps {
shell('#!/bin/bash\n' +
'echo "PRE BUILD SCRIPT"\n' +
'env | sort\n' +
'echo "PRE BUILD END"\n')
}
postBuildSteps {
shell('#!/bin/bash\n' +
'echo "POST BUILD SCRIPT"\n' +
'env | sort\n' +
'echo "POST BUILD END"\n')
}
// Append <runPostStepsIfResult> at the end of the xml
// (which will be just after the closing </postbuilders> tag)
// "it" is a groovy.util.Node representing the
// root <project> element of config.xml.
configure { it <<
'runPostStepsIfResult' {
name('SUCCESS')
}
}
}
In general if you need to add XML which is not supported by Job DSL you can find out what you need by manually configuring a job in Jenkins, then looking at the resultant config.xml
for that job on the Jenkins-master disk. This is usually located at ${JENKINS_HOME}/jobs/job-name/config.xml
The job-dsl playground at http://job-dsl.herokuapp.com/ is a useful place to test changes until you're getting something which matches what Jenkins does in the job/job-name/config.xml file when set manually.
2022 Update
There are methods now available to handle this case without the complexity of a configure
block:
The code above does not appear to compile anymore in the job-dsl playground due to other API changes. With the following modification it does compile however:
mavenJob("example") {
description('MyMavenJob')
goals('install')
preBuildSteps {
shell('#!/bin/bash\n' +
'echo "PRE BUILD SCRIPT"\n' +
'env | sort\n' +
'echo "PRE BUILD END"\n')
}
postBuildSteps {
shell('#!/bin/bash\n' +
'echo "POST BUILD SCRIPT"\n' +
'env | sort\n' +
'echo "POST BUILD END"\n')
}
// Append <runPostStepsIfResult> at the end of the xml
// (which will be just after the closing </postbuilders> tag)
// "it" is a groovy.util.Node representing the
// root <project> element of config.xml.
configure { it <<
'runPostStepsIfResult' {
name('SUCCESS')
}
}
}
Answered By - Ed Randall
Answer Checked By - Robin (JavaFixing Admin)