Conditional environment variables in Jenkins Declarative Pipeline

Viewed 58359

I'm trying to get a declarative pipeline that looks like this:

pipeline {
    environment {
        ENV1 = 'default'
        ENV2 = 'default also'
    }
}

The catch is, I'd like to be able to override the values of ENV1 or ENV2 based on an arbitrary condition. My current need is just to base it off the branch but I could imagine more complicated conditions.

Is there any sane way to implement this? I've seen some examples online that do something like:

stages {
    stage('Set environment') {
        steps {
            script {
                ENV1 = 'new1'
            }
        }
    }
}

But I believe this isn't setting the actually environment variable, so much as it is setting a local variable which is overriding later calls to ENV1. The problem is, I need these environment variables read by a nodejs script, and those need to be real machine environment variables.

Is there any way to set environment variables to be dynamic in a jenkinsfile?

7 Answers

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

Here is a way to set the environment variables with high flexibility, using maps:

    stage("Environment_0") {
        steps {
            script {
                def MY_MAP = [ME: "ASSAFP", YOU: "YOUR_NAME", HE: "HIS_NAME"]
                env.var3 = "HE"
                env.my_env1 = env.null_var ? "not taken" : MY_MAP."${env.var3}"
                echo("env.my_env1: ${env.my_env1}")                 
           }
        }
    }

This way gives a wide variety of options, and if it is not enough, map-of-maps can be used to enlarge the span even more. Of course, the switching can be done by using input parameters, so the environment variables will be set according to the input parameters value.

pipeline {
    agent none
    environment {
        ENV1 = 'default'
        ENV2 = 'default'
    }
    stages {
        stage('Preparation') {
            steps {
                script {
                    ENV1 = 'foo' // or variable
                    ENV2 = 'bar' // or variable
                }
                echo ENV1
                echo ENV2
            }
        }
        stage('Build') {
            steps {
                sh "echo ${ENV1} and ${ENV2}"
            }
        }
        // more stages...
    }
}

This method is more simple and looks better. Overridden environment variables will be applied to all other stages also.

I tried to do it in a different way, but unfortunately it does not entirely work:

pipeline {
  agent any
  environment {
    TARGET = "${changeRequest() ? CHANGE_TARGET:BRANCH_NAME}"
  }

  stages {
    stage('setup') {
        steps {
            echo "target=${TARGET}"
            echo "${BRANCH_NAME}"
        }
    }
  }
}

Strangely enough this works for my pull request builds (changeRequest() returning true and TARGET becoming my target branch name) but it does not work for my CI builds (in which case the branch name is e.g. release/201808 but the resulting TARGET evaluating to null)

Related