Issue
I have two Jenkinsfile for sample: The content of A_Jenkinsfile is:
pipeline {
agent any
stages {
stage("first") {
steps {
script {
foo = "bar"
}
sh "echo ${foo}"
}
}
stage("two") {
steps {
sh "echo ${foo}"
}
}
}
}
The other one is B_Jenkinsfile and its content is:
pipeline {
agent any
stages {
stage("first") {
steps {
script {
def foo = "bar"
}
sh "echo ${foo}"
}
}
stage("two") {
steps {
sh "echo ${foo}"
}
}
}
}
When I build them, B_Jenkinsfile is failed and A_Jenkinsfile is success.
What is differences between either of using def and without using def in Jenkinsfile in script block?
Solution
There are two types of Pipeline syntax. Declarative Pipeline
and Scripted Pipeline
. A declarative pipeline starts with a pipeline {}
wrapper and will have Stages
and Steps
. Declarative pipeline limits what is available to the user with a more strict and pre-defined structure. Where in scripted Pipeline it's more closer to groovy, and users will have more flexibility on what they can do. When you run something in a Script
block in a declarative Pipeline, The script step takes a block of the Scripted Pipeline
and executes that in the Declarative Pipeline. Basically, it runs a Groovy
script for you. So your question can be rephrased as what def
means in a Groovy script.
Simply in a Groovy script, if you omit adding the def
keyword the variable will be added to the current script's binding. So it will be considered as a Global variable. If you use def
the variable will be scoped, and you will only be able to use it in the current script block. There are multiple detailed answers for this here, so I'm not going to repeat them.
Answered By - ycr
Answer Checked By - Terry (JavaFixing Volunteer)