Handling environment variables in gradle

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:

--

--

--

Founder and Senior Android Engineer. Crowdfunding addict. Trying hard to do the right thing and failing more often than not.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sven Bendel

Sven Bendel

Founder and Senior Android Engineer. Crowdfunding addict. Trying hard to do the right thing and failing more often than not.

More from Medium

How Kotlin includes creational design patterns in language features

Kotlin Coroutines: The threading worker — I

Kotlin Coroutines, putting together the pieces

Filter your dependencies artifacts by repository