Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Pipeline Conditional Environmental Variables

Tags:

jenkins

groovy

I have a set of static environmental variables in the environmental directive section of a declarative pipeline. These values are available to every stage in the pipeline. I want the values to change based on an arbitrary condition. Is there a way to do this?

pipeline {
   agent any
   environment {
     if ${params.condition} {
     var1 = '123'
     var2 = abc
    } else {
     var1 = '456'
     var2 = def
     }
   }
   stages {
     stage('One') {
      steps {
        script {
        ...
        echo env.var1
        echo env.var2            
        ...
     }
    }
   }
  }
  stag('Two'){
   steps {
        script {
        ...
        echo env.var1
        echo env.var2
        ...
     }
   }
 }
like image 563
SSF Avatar asked Dec 02 '22 10:12

SSF


2 Answers

Looking for the same thing I found a nice answer in other question:

Basically is to use the ternary conditional operator

pipeline {
    agent any
    environment {
        var1 = "${params.condition == true ? "123" : "456"}"
        var2 = "${params.condition == true ? abc : def}"
    }
}

Note: keep in mind that in the way you wrote your question (and I did my answer) the numbers are Strings and the letters are variables.

like image 100
froblesmartin Avatar answered Dec 18 '22 15:12

froblesmartin


I would suggest you to create a stage "Environment" and declare your variable according to the condition you want, something like below:-

pipeline {
   agent any
   environment {
     // Declare variables which will remain same throughout the build
   }
   stages {
     stage('Environment') {
                agent  { node { label 'master' } }
                steps {
                    script {
                       //Write condition for the variables which need to change
                       if ${params.condition} {
                                 env.var1 = '123'
                                 env.var2 = abc
                                } else {
                                 env.var1 = '456'
                                 env.var2 = def
                                 }
                        sh "printenv"
                    }
                }
            }
         stage('One') {
          steps {
            script {
            ...
            echo env.var1
            echo env.var2            
            ...
         }
        }
       }
      stage('Two'){
       steps {
            script {
            ...
            echo env.var1
            echo env.var2
            ...
         }
       }
    }
    }
}
like image 36
user_9090 Avatar answered Dec 18 '22 13:12

user_9090