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

22 views
Skip to first unread message

fakemai...@gmail.com

unread,
Jul 14, 2021, 11:15:29 AM7/14/21
to Jenkins Users

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 dont want to do this inside of a stage I want this at the top level environment directive for all stages

Ivan Fernandez Calvo

unread,
Jul 14, 2021, 2:05:34 PM7/14/21
to Jenkins Users
the environment is a declarative block, what you are trying to make is to define a bunch of variables with a scriptlet block, this is far away from declarative.
The following code make what you want to do

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
               script {
                   [A:1,B:2].each { k, v ->
                       env."${k}" = "${v}"
                   }
                   echo """
                   A = ${env.A}
                   B = ${env.B}
                   """
               }
            }
        }
    }
}

Reply all
Reply to author
Forward
0 new messages