A Jenkinsfile is a text file containing instructions for building a project and running tests in Jenkins.
A Jenkinsfile is typically used to define a Jenkins pipeline and is checked into source control alongside the rest of the project source code. If the Jenkinsfile is changed, the Jenkins instance will detect the changes and rebuild the project with the instructions specified in the file.
Using a Jenkinsfile helps to automate the build and testing process and ensures that the project is built consistently every time. It also makes sharing and reusing build configurations across different projects easy.
When working with a Jenkinsfile, you may encounter an instance where you need to store values that are used later in the file or referenced by other parts of the script. This is where Jenkinsfile variables come into play.
In this tutorial, we will learn how to use variables in a Jenkinsfile to store values for later use.
What is a Jenkinsfile Variable?
A Jenkinsfile variable refers to a storage container defined and used to store and reference values that are subject to change in the script.
In most cases, we define variables at the beginning of the Jenkinsfile. The variables will contain a global scope meaning they can be accessed at any point in the Jenkinfile.
How to Define a Variable in Declarative Jenkinsfile
Consider the following Jenkinfile that prints out a simple hello world text to the console.
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
}
}
}
}
Suppose we wish to add a variable containing a given string and print it out to the console instead of “Hello world”?
We can start by defining a new variable to hold the message to output to the Console.
In a Jenkinsfile, we define a variable using the def keyword followed by the name of the variable, the assignment operator, and the variable’s value.
For example:
The above example defines a variable called msg holding a string value.
Variables are dynamic. Hence, we do not need to specify the data type during variable declaration.
We can then use the variable as shown:
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo "${msg}"
}
}
}
}
Ensure to enclose the message in quotation marks.
Once we build the pipeline, we should see the text printed in the console as shown:
If you wish to change the value of a pre-defined variable, you can use a script block as shown:
steps() {
script {
msg = "Now the string is different!!"
}
}
}
The following shows the full pipeline definition.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script {
msg = "Now the string is different!!"
}
echo "${msg}"
}
}
}
}
Running the pipeline above should return the text:
Conclusion
In this article, you discovered how to define variables in a Jenkinsfile and learned how to use the variables and modify their values inside a Jenkinsfile.