Read a property from gradle.properties

My Gradle build has a parameter apiKey. When the build is run locally, this parameter should be read from a property in $GRADLE_USER_HOME/gradle.properties

apiKey=secret

When the build is run on a CI server, the property should instead be read from an environment variable named apiKey.

How should I read this property in my build file? I’ve tried the following:

apiKey = System.getenv('apiKey')

But this seems to only look for the property in an environment variable, i.e. a property set in gradle.properties is ignored.

How can I achieve the following?

  1. Get the apiKey value from $GRADLE_USER_HOME/gradle.properties
  2. If (1) fails, get apiKey from an environment variable
1 Like

There’s nothing Gradle-specific about looking for a property in one place, and if it’s not there falling back to another location. You achieve that behavior trying to find the project property, and if it’s not there, gettting it from the environment. One way to write that is

ext.apiKey = project.findProperty('apiKey') ?: System.getenv('apiKey')