5

I'm bit curious for learning how can we load private credentials from system environment variables (Windows/Mac/Linux) in Android build.gradle or any other gradle configuration file. There might be ways or approaches through which we can achieve this but really looking for directions.

Couple of things I already explored but didn't work for me are:

Note: I tried on Windows Environment and getting null.

In Gradle, is there a better way to get Environment Variables?

https://javabydeveloper.com/gradle-system-properties-via-command-line-step-by-step-example/

How to give System property to my test via Gradle and -D

https://dzone.com/articles/specifying-gradle-build

https://discuss.gradle.org/t/how-should-i-be-handling-passing-system-properties-from-gradle-to-my-tests/7171/3

Nah
  • 1,690
  • 2
  • 26
  • 46
  • 1
    What does "didn't work for me" mean? What were your symptoms? Also, where and how are you using Gradle: command line? CI server? Android Studio? Some other IDE? – CommonsWare Oct 17 '21 at 11:13
  • If you need data for signing keys, I would create gradle.properties file and store it in: ~/.gradle/gradle.properties. (on Mac) – I.Step Oct 17 '21 at 11:53
  • I'm using trying to access in `build.gradle` file in Android Studio to fetch system environment variables and I get `NULL` via every approach mentioned in links. – Nah Oct 20 '21 at 20:54
  • This may help: https://stackoverflow.com/a/16414092/6645076 – crazo7924 Oct 24 '21 at 03:56

1 Answers1

5

You can access a variable called MY_VAR using System.getenv('MY_VAR') in a Gradle script. If the variable doesn’t exist, then null is returned. This should work equally well on all platforms.

For example, with the build.gradle script

def myVar = System.getenv('MY_VAR')
println(myVar)

the Gradle command MY_VAR='it works!' ./gradlew projects outputs the following (and some more) on the console (tested in a Linux shell with Gradle 7.2):

> Configure project :
it works!
Chriki
  • 15,638
  • 3
  • 51
  • 66
  • 1
    Quite strange, I get `Null` when I try to access it just like you are doing. – Nah Oct 20 '21 at 20:55
  • I assume you got `null` (all lower-case)? Did you run the _exact same_ command in a Linux bash shell? Are you sure the environment variable is set for the process from which you try to access it? – Chriki Oct 21 '21 at 18:09
  • I am using Windows 10, and once I set the System Environment variable I do not get anything in `gradle` when I run it. Would you try on your Windows please? – Nah Oct 24 '21 at 14:40
  • Unfortunately, I don’t have a Windows system to test this with. However, the issue sounds like the environment variable is simply not correctly made available to the `gradle` process. Do you see the variable when you print the entire set of environment variables in your `build.gradle` (e.g., with `println(System.getenv())`)? – Chriki Oct 25 '21 at 15:57