Handling environment variables in gradle

Sven Bendel
2 min readApr 9, 2018


Oftentimes we find ourselves in the situation of having to pull the values of environment variables into our gradle builds — e.g. to securely provide API keys to use in your code base without having to store them within the repository.

Luckily gradle provides us with a very easy way to do just that.

Providing environment variables

Gradle can easily read environment variables which you have defined on a system level (e.g. via .pam_environment, .zshrc and similar).

However you can also define environment variables just for gradle on a more granular level by means of a local.properties file in your project root.

Just add your new variable in a new line of the file like this:

The local.properties file usually isn’t checked in to your code versioning system, so it stays private which can be important e.g. when working on open source projects.

Reading environment variables

Reading system environment variables is simple. I usually prefer to do that in the buildscript in my project level build.gradle, but you can also do it from any gradle file you want.

Fetching a property from local.properties requires a bit more boilerplate, but isn’t complicated at all as well:

In case you want to be able to provide the token in both ways (e.g. via system environment variable on the CI and via local.properties on your local machine) a simple check like this will do the trick:



Sven Bendel

Senior Android Engineer @Photoroom. Founder. Crowdfunding addict. Trying hard to do the right thing and failing more often than not. https://proven.lol/286e9b