Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scripted Pipeline set and access environment variables

I am using scripted Jenkins Pipeline to execute my build. One of my stages calls ant with parameters to build the executable. I read that I can use withEnv step to pass variables:

node(this.JENKINS_NODE_LABEL) {
    withEnv ([
        'JAVA1_8 = /usr/lib/jvm/java-1.8.0-openjdk',
        'ANT_HOME = ant-1.7.1',
        'ANT_OPTS = -Xmx512m',
        'PATH = $ANT_HOME/bin:$PATH',
        'COMPONENT_NAME = SampleName'
        ]) {
            buildComponent()
        }
}

The buildComponent stage is defined inside an additional file and it contains just one step to execute a build:

def call() {
    stage('Build Component') {
        sh 'ant -Dcomponent=$COMPONENT_NAME'
    }
}

However, when I execute it I am receiving an exception that ant is not recognized and the value passed as the component is empty. I tried to use also env.COMPONENT_NAME but without luck. How should I set and access environment variables inside Scripted Pipeline?

like image 722
Adam Avatar asked May 19 '26 03:05

Adam


1 Answers

I'm not sure if this will completely solve your issue, but I believe it's the first problem: you need to remove the spaces either side of the = in the environment variable strings. It's a list of Strings, rather than a Map of keys to values, so it will be passed as-is to a shell, similar to how you'd pass an environment variable to a command if running it in a shell manually, for example:

MYVAR=value /usr/bin/mycommand

rather than

MYVAR = value /usr/bin/mycommand

A basic example in a pipeline script -- the following will print world:

withEnv(['HELLO=world']) {
    print env.HELLO
}

but this will print null, because of the spaces either side of the =:

withEnv(['HELLO = world']) {
    print env.HELLO
}
like image 59
grdryn Avatar answered May 21 '26 15:05

grdryn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!