Jenkins Pipeline: Conditionally Define Variables – Groovy Script

The Groovy scripting language supports conditional structures, that can be used in Jenkins pipelines.

Assume that you have a parametrized Jenkins job and in a Jenkinsfile you have a variable that should be defined depending on provided parameters.

Here is an example of how to conditionally define variables in a Jenkins pipeline using the Groovy scripting language syntax.

Cool Tip: Jenkins installation and basic configuration! Read more →

Conditional Variables in Jenkins Declarative Pipeline

An example of the Jenkinsfile with the conditionally defined variable:

// Define variables (based on parameters set in a Jenkins job)
// and convert them to lowercase
def role = params.ROLE.toLowerCase()
def env = params.ENVIRONMENT.toLowerCase()

// Conditionally define a variable 'impact'
if (role == 'front' && env == 'prod') {
  impact = "high"
} else if (role == 'front' && env == 'dev') {
  impact = "low"
} else if (role == 'db' && env == 'stg') {
  impact = "medium"
} else {
  impact = "unknown"
}

// Print the 'impact' variable in a Jenkins declarative pipeline
pipeline {
  agent any
  stages {
    stage ("Impact") {
      steps {
        echo "The impact is ${impact}"
      }
    }
  }
}