sajad torkamani

Store credentials

You can store sensitive credentials such as API keys in the encrypted file config/credentials.yml.enc. Run:

./bin/rails credentials:edit

By default, this should open up a file that looks like this:

 # aws:
  #   access_key_id: 123
  #   secret_access_key: 345
   # Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
  secret_key_base: some-secret-here

Rails will use config/master.key or the environment variable RAILS_MASTER_KEY to encrypt this file. Make sure you save the contents config/master.key somewhere (e.g., LastPass) and keep it out of Git.

Access credentials

Given this decrypted config/credentials.yml.enc:

secret_key_base: 3b7cd72...
some_api_key: SOMEKEY
  access_key_id: 1234AB

Rails.application.credentials.some_api_key returns "SOMEKEY" and Rails.application.credentials.system.access_key_id returns 1234AB.

Raise error if credential is missing

Rails.application.credentials.some_api_key! # => KeyError: :some_api_key is blank

Notice the the ! suffix.

You can also do this for nested attributes:



Tagged: Rails