Conditional environment variables in Jenkins Declarative Pipeline

use withEnv to set environment variables dynamically for use in a certain part of your pipeline (when running your node script, for example). like this (replace the contents of an sh step with your node script):

pipeline {
    agent { label 'docker' }
    environment {
        ENV1 = 'default'
    }
    stages {
        stage('Set environment') {
            steps {
                sh "echo $ENV1" // prints default
                // override with hardcoded value
                withEnv(['ENV1=newvalue']) {
                    sh "echo $ENV1" // prints newvalue
                }
                // override with variable
                script {
                    def newEnv1 = 'new1'
                    withEnv(['ENV1=' + newEnv1]) {
                        sh "echo $ENV1" // prints new1
                    }
                }
            }
        }
    }
}

Maybe you can try Groovy's ternary-operator:

pipeline {
    agent any
    environment {
        ENV_NAME = "${env.BRANCH_NAME == "develop" ? "staging" : "production"}"
    }
}

or extract the conditional to a function:

 pipeline {
        agent any
        environment {
           ENV_NAME = getEnvName(env.BRANCH_NAME)
        }
    }

// ...

def getEnvName(branchName) {
    if("int".equals(branchName)) {
        return "int";
    } else if ("production".equals(branchName)) {
        return "prod";
    } else {
        return "dev";
    }
}

But, actually, you can do whatever you want using the Groovy syntax (features that are supported by Jenkins at least)

So the most flexible option would be to play with regex and branch names...So you can fully support Git Flow if that's the way you do it at VCS level.


Here is the correct syntax to conditionally set a variable in the environment section.

environment {
    MASTER_DEPLOY_ENV = "TEST" // Likely set as a pipeline parameter
    RELEASE_DEPLOY_ENV = "PROD" // Likely set as a pipeline parameter
    DEPLOY_ENV = "${env.BRANCH_NAME == 'master' ? env.MASTER_DEPLOY_ENV : env.RELEASE_DEPLOY_ENV}"
    CONFIG_ENV = "${env.BRANCH_NAME == 'master' ? 'MASTER' : 'RELEASE'}"
}

I managed to get this working by explicitly calling shell in the environment section, like so:

UPDATE_SITE_REMOTE_SUFFIX = sh(returnStdout: true, script: "if [ \"$GIT_BRANCH\" == \"develop\" ]; then echo \"\"; else echo \"-$GIT_BRANCH\"; fi").trim()

however I know that my Jenkins is on nix, so it's probably not that portable