LoginSignup
88

More than 5 years have passed since last update.

Rails5.2から導入されたcredentials.yml.encを極める

Last updated at Posted at 2018-11-04

はじめに結論

Rails5.2ではRails newをした際にconfig/secrets.ymlが生成されなくなりました。
代わりにconfig/credentials.yml.encが生成されます。

今回は、credentials.yml.enc及びmaster.keyの使い方についてまとめていきます。

結論、Rails5.2では秘匿情報の取得は、Rails.application.secrets.xxxx ではなく、 Rails.application.credentials.xxxxで可能になります。

編集方法

まず、credentials.yml.encを編集するためにはrails credentials:editコマンドを実行します。

ただ、EDITORが~/.bash_profileなどで未指定の場合は、

$ EDITOR=vim bin/rails credentials:edit

と記述してください。

コマンドを実行すると下記のような初期設定が表示されます。

config/master.key
# aws:
#   access_key_id: 123
#   secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 94cd28a0bbe83b737292da7928f2f5fca17937922b0a79a64c22cc4999d87d3426808ad3ea655e7a68652d6e3e3c1021339ceb87ee615322351640bed63ce8bd

TwitterAPIの情報を記述してみる

config/master.key
twitter
  api_key: abcd1234...
  api_secret: efgd5678...

※secrets.ymlのようにシングルクォーテーションで囲む必要は無いです。

コンソールで値を取得してみる

$ rails c

irb(main):001:0> Rails.application.credentials.twitter[:api_key]
=> abcd1234...

irb(main):002:0> Rails.application.credentials.twitter[:api_secret]
=> efgd5678...

irb(main):003:0> Rails.application.credentials.secret_key_base
=> "94cd28a0bbe83b737292da7928f2f5..."

capistranoで反映させたい

shared/config/master.ymlにmaster.ymlをコピーする必要があるようです。
参考:http://waiyanyoon.com/deploying-rails-5-2-applications-with-encrypted-credentials-using-capistrano/

scpコマンドを使ってEC2に転送しましょう。
参考:https://qiita.com/Yorinton/items/df24281fcf07729fa0f9

$ scp -i path/to/pem  path/to/local_file EC2ユーザ名@IPアドレス:EC2インスタンスの任意のパス

今回はEC2インスタンス内のshared/config/配下にローカルmaster.ymlをコピーしたかったので、下記の用に記述しました。

$ scp -i .ssh/example.pem AppName/config/master.yml ec2-user@xx.xxx.xxx.xx:/var/www/AppName/shared/config/

こちらの設定を行うことでコマンドの記述をさらに短縮できるようです。

デプロイ前の準備

先に本番のshared/config/配下にコピーできた後に下記のコマンドを実行。
linked_filesは配列になっているので、そこにmaster.keyを追加します。

set :linked_files, fetch(:linked_files, []).push("config/master.key")

[本番環境]master keyの存在を確認する設定

本番環境ではmaster keyの指定漏れを防ぐためにconfig/environments/production.rbconfig.require_master_key = trueを有効化することが推奨されてるようです。

config/environments/production.rb
config.require_master_key = true

参考記事

Rails5.2から追加された credentials.yml.enc のキホン

SCPでAWS EC2インスタンスとファイルを送受信する

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
88