Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an environment variable from a Gradle build?

I'm trying to set an environment variable from my Gradle build. I'm on MacOS X (El Capitan). The command is "gradle test".

I'm trying this in my build.gradle:

task setenv(type: Exec) {     commandLine "export", "SOME_TEST_VAR=aaa" } test.dependsOn setenv 

and the build fails:

Execution failed for task ':myproject:setenv'.

A problem occurred starting process 'command 'export''

I also tried this:

test.doFirst {     ProcessBuilder pb1 = new ProcessBuilder("export SOME_TEST_VAR=some test value")     pb1.start(); } 

The build succeeds. However, if I check the environment variable in my JUnit test it fails:

assertTrue(System.getenv().containsKey("SOME_TEST_VAR")); 

Is there any way to set an environment variable from a Gradle build (in the build.gradle file)?

Update:

I've tested it in isolation: the values do get passed and my test task receives everything, be it a systemProperty, environment variables or jvmArgs.

So, it's nothing wrong with Gradle itself here.

The problem arises when I'm trying it on the real project. It uses Spring for dependency injection. I may be wrong but it looks like the Spring framework purges those values somewhere.

That sub-project is currently being frozen and I can't check my guess in detail right now.

like image 460
user3791111 Avatar asked Mar 31 '16 01:03

user3791111


People also ask

How do I set environment variables in Gradle?

Configure your system environment In File Explorer right-click on the This PC (or Computer ) icon, then click Properties -> Advanced System Settings -> Environmental Variables . Under System Variables select Path , then click Edit . Add an entry for C:\Gradle\gradle-7.5\bin . Click OK to save.

How do I set environment variables in Gradle Mac?

Open the system properties (WinKey + Pause), select the “Advanced” tab, and the “Environment Variables” button, then add “C:\Program Files\gradle-x.x\bin” (or wherever you unzipped Gradle) to the end of your “Path” variable under System Properties.


2 Answers

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' } 
like image 32
Guildenstern70 Avatar answered Sep 24 '22 05:09

Guildenstern70


For a test task, you can use the environment property like this:

test {   environment "VAR", "val" } 

you can also use the environment property in an exec task

task dropDatabase(type: Exec) {     environment "VAR", "val"     commandLine "doit" } 

Note that with this method the environment variables are set only during the task.

like image 66
Ortomala Lokni Avatar answered Sep 26 '22 05:09

Ortomala Lokni