Skip to content

Instantly share code, notes, and snippets.

@trouni
Last active August 27, 2021 05:29
Show Gist options
  • Save trouni/f0a92868fef32dd6dedbe805f89216f8 to your computer and use it in GitHub Desktop.
Save trouni/f0a92868fef32dd6dedbe805f89216f8 to your computer and use it in GitHub Desktop.
Use a credential file on Heroku

How to use a credential file on Heroku (json, yml, etc.)

  1. 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)
  1. 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'
  1. (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!

Bonus: Escape special characters

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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment