I am recently refactoring a groovy Jenkins script to declarative and I noticed that many limitations that apply to the script within the pipeline{} block, do not apply to the functions defined outside it, even though the function is being called from inside the declarative script.
For example :
stages {
stage ("${any_stage_name}") {
...
...
}
}
The above will give error in declarative pipeline since it does not support variables as stage names currently, but declaring a stage - with a variable as a name - in a function will work just fine !
def sampleFunc() {
stage ("${any_stage_name}") {
...
...
}
}
Similarly, for loops can also be used in a function but not within the declarative script itself.
Are user defined functions loaded by default as a groovy class and executed in its run method ??
I am looking for a detailed explanation as to why this happens !
PS: I am extremely new to jenkins.
for scripted pipeline and declarative pipeline used different AST parsers(tool which detects where is variable where is start of block where is end, where is if statement etc) and how they translated and executed. and in declarative first starts syntax validation then variable evaluation
here detailed explanation
also see this
https://www.youtube.com/watch?v=i9pNYW1Pg9A
you will understand why and how it works under the hood also recommend you read about delegates/closures in groovy https://www.youtube.com/watch?v=fdpKCuJKbMg
this is basic concept