Dragon Arrow written by Tatsuya Nakaji, all rights reserved animated-dragon-image-0164

Rails5.2 credentials

updated on 2019-04-17

イメージ


目的: database.ymlやdatabase.ymlなどの各ファイルで、環境変数として機密情報を隠したいときに使える


credentials.yml.encの内容は暗号化されてるためcredentials.yml.encを編集するためにはeditor=vim rails credentials:editコマンドを実行します。


# credentials.yml.encをviで開く
$ EDITOR="vi" bin/rails credentials:edit


credentials.yml.enc

db:
  host:     xxxxx
  database: xxxxx
  username: xxxxx
  password: xxxxx
aws:
  access_key_id: xxxxxxx
  secret_access_key: xxxxxxx
secret_key_base: xxxxxxx


config/database.yml

# 省略
production:
  <<: *default
  # 省略
  host:     <%= Rails.application.credentials.db[:host] %>
  # host:     <%= Rails.application.credentials.dig(:db, :host) %>でも良い
  database: <%= Rails.application.credentials.db[:database] %>
  # database:     <%= Rails.application.credentials.dig(:db, :database) %>
  username: <%= Rails.application.credentials.db[:username] %>
  # username:     <%= Rails.application.credentials.dig(:db, :username) %>
  password: <%= Rails.application.credentials.db[:password] %>
  # password:     <%= Rails.application.credentials.dig(:db, :password) %>


config/database.yml

# 省略
amazon:
service: S3
access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
region: ap-northeast-1
bucket: mybucket


暗号化するときの鍵は RAILS_MASTER_KEY という環境変数に格納

$ export RAILS_MASTER_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$ rails c

irb(main):001:0> Rails.application.credentials.secret_key_base
=> xxxxx..


Editor指定がめんどい...

$ EDITOR=vi bin/rails credentials:edit

.bash_profileなどに環境変数:EDITORを指定しておけば、EDITOR="xxx"の指定は不要になります。

# .bash_profileに環境変数 EDITOR を設定する
$ echo 'export EDITOR="vi"' >> ~/.bash_profile
$ source ~/.bash_profile
$ echo $EDITOR
  #=> vi

$ bin/rails credentials:edit