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

3 Replies to “Jenkins Pipeline: Conditionally Define Variables – Groovy Script”

  1. Thanks a lot for this post , it helped me in my task completion.

  2. Thank You so much

  3. Nice, help me alot

Leave a Reply