Tuesday, 23 January 2018

Remove your secret from your source code to system env ---- gradle load system env into android source code

I will help you to setup this on your local development pc first:

Below changes will make sure you can extract your secrets(api keys) out from your sourcecode, and still do coding and testing as normal, no extra jobs to do (ofcause only the very first time or if you want to change these secrets)

Check this to see how to get values from gradle.property file:


below link will tell you how to get system evn in gradle:


However this doesn't work on mac if you do set env in .bash_profile.


You will need to find another way to set env:


for mac 10.10+




My Mac settings:

Create a plist file under ~/Library/LaunchAgents/

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <string>launchctl setenv APIKEYXXX wangpingccccc
      launchctl setenv APIKEY_DEV aa_dev
      launchctl setenv APIKEY_STAGING aa_staging
      launchctl setenv APIKEY_PROD aa_prod


Setup different value for APIKEY for different environment. 

After you changed this file you will need to restart your computer, and make sure your computer doesn't open you android studio automatically. if it does, please restart your android studio.

Restart you computer will help us to check and make sure this file will help us setup ENV after reboot.

If happy with rebooting and it can setup all ENVs, then if you want to do a quick change without reboot, you can run below commands:

launchctl stop ~/Library/LaunchAgents/my.startup.plist 
launchctl unload ~/Library/LaunchAgents/my.startup.plist 
launchctl load ~/Library/LaunchAgents/my.startup.plist 

launchctl start ~/Library/LaunchAgents/my.startup.plist 

Load them into gradle

def API_KEY_DEV = '"' + System.getenv('APIKEY_DEV') + '"' ?:'"default Dev api key"'def API_KEY_STAGING = '"' + System.getenv('APIKEY_STAGING') + '"' ?:'"default Staging api key"'def API_KEY_PROD = '"' + System.getenv('APIKEY_PROD') + '"' ?:'"default Prod api key"'

and then put them into different build variants:

Then click this to sync your gradle:

Depends on which Build Variant are you on, then you can find this:

I am on staging variant:

then i can use it in my code like this:

and it will print out like this:

If i change to dev build Variant, it print out:

I also can use the same way to make AndroidManifest.xml to access these system ENVs:

as you can see it has quotas in the name of the application, i believe you know how to remove it.

Finally, if you push this code to CI, it will not be able to build your code, what you need to do is just set above env vars into your CI's env

No comments:

Post a comment