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.
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.
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.
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
The flow of referencing environment variables is summarized below.
- Decrypt credentials.yml.enc with master.key in local environment
- Edit credentials.yml.enc and set access_key_id and secret_access_key.
- Deploy to production environment
- Set the contents of master.key in the environment variables of the production environment.
- 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!