[Ruby] Change the image save destination to S3 in the Rails application. Part 2

1 minute read

Introduction

It is a continuation from previous article.

Securely handle AWS keys

To prevent the AWS key from being leaked, set the key contents in environment variables. If you don’t know the environment variables, go check it out!

AWS key settings

There was a description such as [:access_key_id] and [:secret_access_key] in carrierwave.rb. A preset key is entered here, and in Rails 5.2 it is managed by a file called “credentials.yml.enc”.

Now open credentials.yml.enc in an editor. You should see the encrypted string as shown below. Screenshot 2020-07-26 23.23.21.png

Set this so that VS Code can be started from the terminal. In VSCode, press “Command + Shift + P” at the same time to open the command palette. Then type “shell”. In the menu, the item “Install’code’ command in PATH” is displayed. Click it. By doing this, you can start VS Code by typing “code” from the terminal.

Now, execute the following command from the terminal. The decrypted credentials.yml.enc should now be visible in VS Code and editable.

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

Edit AWS access_key_id and secret_access_key as follows. dcEU4PX7s6ICcTD1595774207_1595774265.png

master.key settings

credentials.yml.enc decrypts with a file called master.key. However, placing master.key in the production environment is a security problem. Therefore, let’s set the contents of master.key in the environment variable of the production environment.

Log in to the EC2 instance and open the file that sets the environment variables.

sudo vim /etc/environment

Copy the value of “config/master.key” in the local development environment and set it to RAILS_MASTER_KEY in the production environment.

RAILS_MASTER_KEY='master.key value'

Now that the environment variables have been set, let’s log in to the EC2 instance again and check the environment variables with the following command.

env | grep RAILS_MASTER_KEY

Summary

The flow of referencing environment variables is summarized below.

  1. Decrypt credentials.yml.enc with master.key in local environment
  2. Edit credentials.yml.enc and set access_key_id and secret_access_key.
  3. Deploy to production environment
  4. Set the contents of master.key in the environment variables of the production environment.
  5. Production environment credentials.yml.enc can be decrypted using environment variables.

With the previous article and above settings, you should be able to upload images to S3! Perhaps! that’s all!