Is It Possible to Set Environment Variables on a Groovy Function

I know I can have an environment section on jenkins pipeline (declarative) for a stage. Like this:

stage('Name') {
    environment {
        NAME = value
    }   
    steps {
        script {
            Do something using these env vars
        }
    }
} 

I want to write a groovy function, to define some env vars, and run something, and call it from a few pipelines. Something like:

def function () {
    environment {
        NAME = value
    }
    sh "do something using these env vars"
}

Is it possible somehow?

(I know I can write sh "ENV=value; some CMD" but I have few variables, and it is less read-able).

2 Answers

Yes, you can do this. Jenkins Pipeline stores its environment variables in a map named ENV. Therefore, you can add additional key value pairs to this map for additional environment variables. This would be done in Groovy syntax via:

// syntax option one
env.key = value
// syntax option two
env['key'] = value

For your example, this would look like:

def function () {
  env.NAME = value
  sh "do something using these env vars"
}

To create a function that can be shared by several pipelines, you need to place it to a Shared library.

See

To pass environment variables to the sh:

withEnv(['var_name=var_value', 'var_name_2=var_value_2']) {
    echo "process to be executed with var_name=$var_name var_name_2=$var_name_2"
    sh 'bin/start'
}

see

withEnv you should be able to use in the files in var folder of your shared library.

In the classes (in the src folder of your library) you probably neeed to go with the ProcessBuilder. See

def pb = new ProcessBuilder('script_path','arg1','arg2')
pb.environment().put('var_name','var_value')
pb.environment().put('var_name2','var_value2')
Process p = pb.start()
p.waitFor()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest