Jenkins Pipeline: How to Define a Variable – Jenkins Variables

Variables in a Jenkinsfile can be defined by using the def keyword.

Such variables should be defined before the pipeline block starts.

When variable is defined, it can be called from the Jenkins declarative pipeline using ${...} syntax.

Cool Tip: Define conditional variables in a Jenkins pipeline! Read more →

Define a Variable in Jenkins Declarative Pipeline

Here is an example of how to define a variable in a Jenkinsfile and print this variable in a Jenkins declarative pipeline:

// Define variable
def myVariable = "foo"

// Print variable
pipeline {
  agent any
  stages {
    stage ("Print variable") {
      steps {
        echo "My variable is ${myVariable}"

4 Replies to “Jenkins Pipeline: How to Define a Variable – Jenkins Variables”

  1. But how do I change the value of the variable? And what if the variable is not a string?

  2. In the following sample, env.MYVAR will contain the stdoutput

    steps {
             script {
                 env.MYVAR = sh( script: "./",
                                 returnStdout: true).trim()
                 echo "MYVAR: ${env.MYVAR}"
  3. Thanks , it worked, the variable assignment should be inside script block.

  4. How to use jenkins paramters in Jenkinsfile.groovy.

Leave a Reply