Sourcing environment variables on node

22 views
Skip to first unread message

Christoph Ruepprich

unread,
Nov 2, 2017, 1:59:42 PM11/2/17
to Jenkins Users
Hi all,
on a remote node I have a file that exports some variables:
$ cat myenv
export FOO=Hello
export BAR=World

My pipeline script tries to source that file, but the variables don't seem to stick:
node ('remote-server') {
    sh ('. /home/cmr/myenv')
    echo "My Variables: ${env.FOO} ${env.BAR}"
}

Output:
[set-remote-env] Running shell script
+ . /home/cmr/myenv
++ export FOO=Hello
++ FOO=Hello
++ export BAR=World
++ BAR=World
[Pipeline] echo
My Variables: null null


When I source directly from the server's command prompt, the variables stick:
$ . myenv
$ echo "My Variables: $FOO $BAR"
My Variables: Hello World
$




How can I source environment variables in my pipeline script?

Thanks!







itchymuzzle

unread,
Nov 2, 2017, 3:01:04 PM11/2/17
to Jenkins Users
Maybe something like this?

node ('remote-server') {
    sh '''
       . /home/cmr/myenv'
    '''
}

Christoph Ruepprich

unread,
Nov 2, 2017, 3:58:47 PM11/2/17
to Jenkins Users
Thanks ichymuzzle. It worked with a minor change.
So the problem is that each sh looses it's environment. Is there a way to set it globally?


node ('remote-server') {
    sh ('''
       . /home/cmr/myenv
       echo "My Variables: $FOO $BAR"
    ''')

itchymuzzle

unread,
Nov 2, 2017, 4:07:38 PM11/2/17
to Jenkins Users
Don't know how to set it globally, most likely someone will know how to do that and respond.

> each sh looses it's environment.

Each sh is it's own environment.  If you have two different terminals up, what you do in one isn't known in the other. For example.

Robert Hales

unread,
Nov 3, 2017, 12:40:39 AM11/3/17
to Jenkins Users
Yeah, as you found, the environment is the sh is only present during that run. It is just like dropping to a shell (or running another shell within a shell), running some things, and then exiting. 

If you want to set them globally, you will need to set them in an environment block in declarative pipeline, or in groovy code. env.FOO = "BAR". 

If you want to try to set something in the shell, and then get those values back into the pipeline, it gets a little harder. You can return just a value from a shell script and assign that to a variable. Or you can look at the pipeline utility steps plugin to suck things in from a file. 
Reply all
Reply to author
Forward
0 new messages