The answer by souravatta is correct but i use a different approach and will like to share with an example.
//define the variable globally so that can be used by a fuction as well as pipeline somevalue1=""; somevalue2=""; somevalue3=""; somevalue4=""; pipeline{ environment{ releasevalue = "r5" depenv = "dev" servicename = "Myservice" setecsvalues = settingvalues(releasevalue,depenv,servicename) } agent any stages{ stage(testing){ steps{ echo "${releasevalue}" echo "${depenv}" echo "${servicename}" echo "${somevalue1}" echo "${somevalue2}" echo "${somevalue3}" echo "${somevalue4}" } } } } //Setting Values from this function, you can write any program here to dynamically set values or maybe read from an external file def settingvalues(releasevalue,depenv,servicename){ //some code to set values dynamically somevalue1 = value1 somevalue2 = value2 somevalue3 = value3 somevalue4 = value4 }
It contains some more things from what you have asked for so bear with me :)
In environment block I have written 3 values and one function. You can simply write the values and use it inside any stage.
You can write a function and return a value by setting it dynamically. Here I am not returning anything because I wanted to set 4 values instead of returning a single one.
On top I have defined 4 values, that can be used by the function as well as inside the pipeline.
TIP
If you hardcode the values of variables inside the Jenkinsfile, that is not a good solution. Instead what you need to do is create a file, JSON or Yaml. Put it in a common location and use readJSON or readYaml to read those files and extract values dynamically. this way if you have to manage a lot of applications with many values then you can simply use one file to place all the values. This can come in handy and saves a lot of time as you do not want to edit your Jenkisnfile very often.