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.

ext.apiToken = System.getenv('API_TOKEN')
// replace the ext. prefix with def if you don’t want to provide the API token to the default properties which you can then access from all your build scripts

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

Properties properties = new Properties()
def propertiesFile = project.rootProject.file('local.properties')
if (propertiesFile.exists()) {
ext.apiToken = properties.getProperty('api.token')

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:

def localPropertyApiToken =// read api token from local.properties
def systemEnvApiToken =// read api token from system environment variable
ext.api_token = localPropertyApiToken != null ? localPropertyApiToken : systemEnvApiToken

Did you find this article valuable?

Support Sven Bendel by becoming a sponsor. Any amount is appreciated!