LoginSignup
0
0

More than 1 year has passed since last update.

Railsにおける秘密情報の管理をざっくり掴む

Last updated at Posted at 2021-12-21

概要

Railsを学習していると、秘密情報の管理方法がたくさんあってどれを使えばいいのか分からなくなってしまうことが多々ありました。
そこで、各バージョンで使用されている手法をまとめてみました。

秘密情報とは何か

秘密情報とは、パスワード、トークン、暗号キーなど外部に公開すべきでない情報のことを指します。
例えばAWSのアクセスキーなども秘密情報に含まれます。

結論

Rails5.2以降はcredentialsで管理をしています。
それ以前では、
Rails4.1:serets.yml
Rails5.1:encrypted secrets
などが使用されていました。

credentialsの使い方

config/credentials.yml.encにYAMLファイルとして暗号化され、秘密情報が保存されています。
ここで暗号化されたファイルを復元するには、Rails newの際に作成されたmaster.keyを使用します。

編集方法は、

% EDITOR=vim rails credentials:edit

VScodeで編集したい場合は、

EDITOR="code --wait" bin/rails credentials:edit

とエディタの指定を変更してください。
参考:Rails5.2のrails credentials:editを好きなエディタで編集する(macOS)

エディタ環境変数にエディタが指定されていないと以下のエラーが出てきます。
その場合は、EDITERに何かしら指定してあげましょう。

No $EDITOR to open file in. Assign one like this:

EDITOR="mate --wait" bin/rails credentials:edit

For editors that fork and exit immediately, it's important to pass a wait flag,
otherwise the credentials will be saved immediately with no chance to edit.

credentials.yml.encの初期設定は以下のようになっています。

credentials.yml.enc
# 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: e3a358ac35037fe43907a8e673e521ff838fko4mdd895b9c6f447efg3db24b008ce23aa22f1b5512c74fcdcf6587c879edaeb5eedf23f835887d8463e4eeda

あとは、設定したい秘密情報を設定すれば設定完了です。

credentials.yml.enc
 aws:
   access_key_id: hoge
   secret_access_key: example
irb(main):001:0> Rails.application.credentials.aws[:access_key_id]
=> "hoge"
0
0
0

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
0
0