Rails credentials

Rails credentials

enmanuelm19@gmail.com2018-06-18 12:37:21 UTC

Rails credentials


Rails credentials exists since version 5.2, before this the usual thing to do was to put our credentials of third party APIs in environment variables, either handle the enviroment variables of the system or creating a .env file with the DotEnv gem. Now we only have to register a master key and our credentials will be encrypted. This give us the posibility of have our credentials encrypted in our repositories without lack of security.

To make use of rails credentials you have to have the master key inside config/master.key, if you don't have a master key you can generate it running the following command and taking the first 32 characters.

rails secret

Paste the generated key inside config/master.key. Important: Put inside .gitignore the file master.key to avoid uploading the file in the repository.

After the key was been generated just need to register the credentials we want, for that we run the following command:

EDITOR=nano rails credentials:edit

This will open the nano editor(you can use the text editor you want) and it will be show a file with the following structure:

aws:
  access_key_id: random_key_id
  secret_access_key: random_access_key

secret_key_base: random_number

Save it and it will create an encrypted file in config/credentiasl.yml.enc, to edit this credentials jus need to run the same commad for create them.

If you want to read the credentials just put the following:

Rails.application.credentials.aws

This will return a hash { access_key_id: random_key_id, secret_access_key: random_access_key }, to keep accessing the other keys, you can acces like any oter hash in ruby, Rails.application.credentials.aws[:access_key_id] that it will return random_key_id

In this way we have our credentials saved safely, we just need to save in a secure place our master key.


Any doubt, advice o correction, you can comment below.


Share