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}"
      }
    }
  }
}
Was it useful? Share this post with the world!

6 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?

    1. you do it inside a script { } block
      i.e.

      myVar = "aaa"
      stage () {
        steps() {
          script {
            myVar = "bbb"
          }
        }
      }
      
  2. In the following sample, env.MYVAR will contain the main.sh stdoutput

    steps {
             script {
                 env.MYVAR = sh( script: "./main.sh",
                                 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