Issue
I am using scripted pipeline and trying to put my stage inside a function as below.
node{
if(value=="true")
{
def func(){
stage ('first stage')
}
}
fun() #calling it here.
}
its not working. it says method definition not expected here
Method definition not expected here. Please define the method at an appropriate place or perhaps try using a block/Closure instead.
. How to do this? its not possible to define outside node block as the pipeline is running on a particular node.
Solution
Without executing the stage, you can return the stage configurations from a function. Please refer to the following.
node {
stage('Stage 1') {
echo "This stage executed always"
}
def value = true
// Lets execute stage 2
if(value == true) {
generateStage("Stage 2").call()
}
stage('Stage3') {
echo "Stage 3"
}
}
def generateStage(name) {
return {
stage("Stage ${name}") {
echo "Stage ${name}"
}
}
}
Answered By - ycr
Answer Checked By - Katrina (JavaFixing Volunteer)