DEV Community

Gustavo Alberto
Gustavo Alberto

Posted on

How to store credentials like an api key in Rails

Who here ever wanted to storage credentials like an env variable to use in your application. So your problems are over. Rails provides us a tool to store our credentials using encryption. Without further ado, let's get down to business.

Once you have your rails project already created use this command line in the terminal running in your root of your rails project.

EDITOR="nano" rails credentials:edit

If you are running this command for the first time, it will create a master.key, which is a key for encrypting and decrypting your credentials.

After running it will open the editor that you choose inside the parameter EDITOR in command line, the editor will open in the file that stores the credentials, then you can store your variables in yml format like this:

api_key: 7647hddggsadasb-afdafd-nfs
aws: 
   access_key_id: 123
   secret_access_key: 345
Enter fullscreen mode Exit fullscreen mode

Then save it with your editor and your credentials are stored sucessfully.

To access this variables in your code follow this example:

Rails.application.credentials.api_key
Rails.application.credentials.aws.access_key_id
Rails.application.credentials.aws.secret_access_key
Enter fullscreen mode Exit fullscreen mode

You can edit your credentials with the same command:

EDITOR="nano" rails credentials:edit

Simple isn't it? With Rails everything is much easier.

Thanks for reading this post :)

Top comments (0)