how to use google api keys based on heroku application name
I've created a few different "environments" for开发者_Python百科 my app that is hosted on heroku so I have: appName-staging.heroku.com appName-production.heroku.com
I want to use different google api keys for these applications, how do I do this? i've created a google.yml file that looks like:
development: api_key: 'ABCXYZ'
production: api_key: 'DEFXYZ'
so I use ABCSZY when developing locally, and DEFXYZ for appName-production.heroku.com question is, how do i get appName-staging.heroku.com to use a different key?
since every application deployed to Heroku is considered to be in "production", both appName-staging.heroku.com and appName-production.heroku.com use the same key.
You could add a heroku config variable to each environment, allowing you to identify each one from within the app.
Something along the lines of:
$ heroku config:add APP_NAME_ENV=production --app appName-production
$ heroku config:add APP_NAME_ENV=staging --app appName-staging
Then you could grab the current environment from within your app using:
ENV['APP_NAME_ENV']
And if you've got your YAML file as a hash called something like GOOGLE_KEYS
, the following would return the correct key for a given environment:
GOOGLE_KEYS[ENV['APP_NAME_ENV']]
The previous answer definitely works but doesn't account for the potential security threats which come with checking files which include private keys into source control. Having your google.yml file in source control will allow anyone with access to your repo to see your private API keys.
A more secure solution would be to delete the google.yml file and create different environment variables on your staging and production servers with the same key:
$ heroku config:add GOOGLE_API_KEY=<production key> --app appName-production
$ heroku config:add GOOGLE_API_KEY=<development key> --app appName-staging
Then, when this is needed you can refer to it in code via
ENV['GOOGLE_API_KEY']
This will allow you to share code without sharing your private API keys.
Some more information on using environment variables on Heroku can be found at https://devcenter.heroku.com/articles/config-vars
精彩评论