3

Is there any gradle function/plugin to read/bind some secret properties (api keys, passwords) from special config/properties files?

For instance, in android plugin you can set properties in ~/.gradle/gradle.properties file:

apiKey=SUPER_SECRET_VALUE

than in project build.gradle:

android {
    buildTypes {
        debug {
            buildConfigField "String", "API_KEY", apiKey
        }
    }    
}

And in project itself you use BuildConfig.API_KEY string constant.

Is there any similar solutions in gradle for other (java) projects?

Or may be this approach is wrong and some other workaround should be used?

radistao
  • 14,889
  • 11
  • 66
  • 92

2 Answers2

1

You can always filter files. You pass resources or source files through a copy command and replace tokens like @API_KEY@ (with filter and ReplaceTokens) or ${API_KEY} (using expand) with Gradle variables.

For example:

processResources {
    filter(ReplaceTokens, tokens: [API_KEY: apiKey])
}

Would replace the substring @API_KEY@ with your actual API key in any of your resource files.

John Zeringue
  • 705
  • 3
  • 13
  • it looks like old-school Ant-Maven solution, but i'm looking for something modern and actual – radistao Sep 26 '16 at 07:41
  • What specifically don't you like about this solution other than you think it's old-school? Android's doing roughly the same thing for you. The only real difference is it seems Android's generating source code, while `filter` is only modifying resources. You could even use this technique to replace values in Java files. – John Zeringue Sep 26 '16 at 11:13
  • In this solution i don't like exactly this: "Android's generating source code, while filter is only modifying resources" :) – radistao Sep 26 '16 at 11:17
0

As an alternative to my prior answer, you can write a custom Gradle task that uses CodeModel. Here's an example.

John Zeringue
  • 705
  • 3
  • 13