[Ruby] [Rails] Manage secret keys etc. with credentials.yml

2 minute read


Here is a reminder about the credentials that appeared in Rails 5 series.

What are credentials?

This is a file to store the private key etc.

The contents of this file are encrypted by master.key, so anyone who does not know the correct master.key cannot see the contents.

The contents of credentials can be called as a variable in other files if there is master.key information, so it is convenient to put the API key etc. in this file.

The master.key and credentials files are automatically created when you rails new, and master.key is included in .gitignore by default, so there is no worry about leaking from github.

Advance preparation

This time, we assume that you use VScode.

First, open the palette with command + shift + P in VScode. Then type shell in the search box and install the shell.

Now you can edit the credentials file with VScode from the terminal.

How to set

Open the credentials file in VScode with the following command.


$ EDITOR='code --wait' rails credentials:edit

By default, the first three lines are commented out in the example, so it’s OK if you imitate it.


  access_key_id: 123
  secret_access_key: 345q

The first line describes what kind of group it is, and the second and third lines describe the id and access key. The contents of the group need to be indented.

You can set more than one, so try setting it.


  access_key_id: 123
  secret_access_key: 345q

  email:'[email protected]'


You need to close the VScode tab to save the credentials file. When closed and saved correctly, the following message will be displayed in the terminal. New credentials encrypted and saved.

How to call

To call the contents, write the following in the ruby file.

Rails.application.credentials[:group name][:contents]

In this example, it can be used as follows.


You can check it on the console from the terminal, so it is good to check it when you edit the credentials file. Open the console with rails c and check. cb6ac75e17de6feb8c00047fc7b39d02.png You can call it properly.


When developing a team, sharing the master.key allows other people to see and edit the contents of the credentials. I think it is better to share master.key with a message application.

However, even if you are a trusted friend, you should not share the aws id and access key that you have in your credentials. (Think of it as sharing your credit card number and verification code.)

Carefully judge what information you need to share and what you don’t. Don’t regret it if you are betrayed and develop like Kaiji! Lol