Issue
I'm using Jenkins and I want to add a post-build action to my dynamically generated stages.
I dynamically generate stages by looping over a configuration file I have by doing this:
stage('run list'){
steps {
script {
...
def stages = stagelist.collectEntries {
["${it}": generateStage(it)]
}
...
}
}
}
Where generateStage is defined as:
def generateStage(job){
return {
stage("${job}"){
catchError(){
....
}
post {
...
}
}
}
}
Which works fine for the stages I have currently. However, when I try to add a post-action to my generate stage function I get NoSuchMethod error.
If I could get some help on this it would be greatly appreciated!
Solution
When you use static parallel steps it is possible to use the post
directive as part of the pipeline syntax, but when you are creating the stages dynamically (in the generateStage
) you are doing so by using the scripted pipeline syntax which Does not support the post
directive.
What you can do instead is use the scripted pipeline version of the post
section using the try
catch
finally
syntax to achieve a similar result to that you would achieve using the post
section in a declarative pipeline.
Try something like:
def generateStage(job){
return {
stage("${job}"){
try {
// Your Execution steps
...
// This is equivalent to the 'success' section in the post directive
}
catch(Exception ex) {
// This is equivalent to the 'Failure' section in the post directive
}
finally {
// This is equivalent to the 'always' section in the post directive
}
}
}
}
It is not hundred precent equal, as the try catch
will only detect exception and wont detect direct build result change - but it should work for the majority of steps
Answered By - Noam Helmer
Answer Checked By - Mildred Charles (JavaFixing Admin)