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}"
      }
    }
  }
}

2 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 main.sh stdoutput

    “`steps {
    script {
    env.MYVAR = sh( script: “./main.sh”,
    returnStdout: true).trim()
    echo “MYVAR: ${env.MYVAR}”
    }
    }“`

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.