- Add an initializer file to write the credentials file
# config/initializers/json_credentials.rb
filepath = './credentials.json'
File.write(filepath, ENV['YOUR_JSON_CREDENTIALS']) unless File.exists?(filepath)
- Set the environment variable on Heroku
heroku config:set SOME_JSON_CREDENTIALS='{"key":"value"}'
Should work with multiline strings too:
heroku config:set YAML_CREDENTIALS='key1:
key2: value
a_list:
- first_element
- "second element"
- boolean: true'
- (Optional) Store the content of the file in your .env (not needed if you already have the credentials file locally)
YOUR_JSON_CREDENTIALS='{"key":"value"}' # content of the json file inside of single quotes
Don't forget to add the credentials file to your .gitignore
!
In case you need to escape special characters (to store a YAML
file in your .env
for example), an easy way to get the escaped version of a file is to copy-paste the content as a string in irb
:
# irb
[1] pry(main)> 'key1:
key2: value
a_list:
- first_element
- "second element"
- boolean: true'
=> "key1:\n key2: value\n a_list:\n - first_element\n - \"second element\"\n - boolean: true"
Use the resulting string when setting the environment variable in your .env
:
# wrap the string in single quotes
YAML_CREDENTIALS='key1:\n key2: value\n a_list:\n - first_element\n - \"second element\"\n - boolean: true'