[gradle] 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.

This question is related to gradle environment-variables build.gradle

The answer is


This looks like an old thread but there is one more variant of how we can set an environment variable in the Gradle task.

task runSomeRandomTask(type: NpmTask, dependsOn: [npmInstall]) {
    environment = [ 'NODE_ENV': 'development', BASE_URL: '3000' ]
    args = ['run']
}

The above Gradle task integrates the Gradle and npm tasks.

This way we can pass multiple environment variables. Hope this helps to broaden the understanding which the answers above have already provided. Cheers!!


If you have global environment variables defined outside Gradle,

test {
    environment "ENV_VAR",  System.getenv('ENV_VAR')
    useJUnitPlatform()
}

Please try this one option:

 task RunTest(type: Test) {
         systemProperty "spring.profiles.active", System.getProperty("DEV")
         include 'com/db/project/Test1.class'
     }

In case you're using Gradle Kotlin syntax, you also can do:

tasks.taskName {
    environment(mapOf("A" to 1, "B" to "C"))
}

So for test task this would be:

tasks.test {
    environment(mapOf("SOME_TEST_VAR" to "aaa"))
}

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

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

This one is working for me for settings environment variable for the test plugin

test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)                
    }    
}

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.


In my project I have Gradle task for integration test in sub-module:

task intTest(type: Test) {
...
system.properties System.properties 
...

this is the main point to inject all your system params into test environment. So, now you can run gradle like this to pass param with ABC value and use its value by ${param} in your code

gradle :some-service:intTest -Dparam=ABC

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.

enter image description here

Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.


Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

Examples related to build.gradle

Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Android dependency has different version for the compile and runtime Setting up Gradle for api 26 (Android) What's the difference between implementation and compile in Gradle? More than one file was found with OS independent path 'META-INF/LICENSE' Android Studio - Failed to notify project evaluation listener error Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2 All com.android.support libraries must use the exact same version specification DELETE_FAILED_INTERNAL_ERROR Error while Installing APK