Search code examples
jenkinsjenkins-pipelinejenkins-pluginsjenkins-groovy

Loop over a list of environment variables inside the environment directive at start of pipeline


I haven't found any examples of how to do this.

Instead of this

pipeline {
    agent { label 'docker' }
    environment {
        ENV1 = 'default'
        ENV2 = 'default'
    }

I want to do this:

pipeline {
    agent { label 'docker' }
    environment {
        for (env in envs) {
           env.name = env.value
        }
    }

Maybe I can generate a map before the pipeline{} directive and pass it to environment{} somehow? I don't want to do this inside of a stage, I want this at the top level environment directive for all stages.


Solution

  • According to the environment directive Documentation it is not possible to execute any code inside the environment block, however you can achieve something similar by creating a custom step and updating the relevant environment variables using a script block and any groovy code your want for updating the env dictionary that contains the environment values.
    Something like:

     pipeline {
        agent { label 'docker' }
        stages {
            stage('Prepare Environment') {
                steps {
                    script{
                        envParams = ['param1': 'value1','param2': 'value2']
                        envParams.each { key ,value ->
                            env[key] = value
                        }
                    }
                }
            }
            ...
        }
    }
    

    This will affect the environment parameters for all stages in the pipeline not just the Prepare Environment stage.

    Another simple option will be just to run a similar code at the top level of the pipeline before execution the starts, it will have the same effect as the previous option, with a somewhat cleaner look for the pipeline itself. Something like:

    ENV_PARAMS= ['param1': 'value1','param2': 'value2']
    ENV_PARAMS.each { key ,value ->
        env[key] = value
    }
    
    pipeline {
        agent { label 'docker' }
        ...
    }