Railsで定数設定ファイルをgitから外して管理する方法。
定数設定ファイルから環境変数に読み込みを行って、gitには乗せられない重要な設定の管理を行います。
Capistranoなんかでデプロイを行おうとすると、設定ファイルがgit管理下に存在していて欲しくありません。 特にパスワードなど他の人に見せたらいけない情報が乗っているなら尚更です。 githubなんかにそのままpushしちゃうとセキュリティ的にも危ないですね。 これを回避するために、設定ファイルをgitの管理下から外し、producitonサーバーへ直接送りつけるのが一番良いのではないでしょうか?
今回はそんな重要な設定情報をカンタンに環境変数としてymlファイル1つで管理できちゃう方法を書いてみます! gemすら追加でインストールする必要はありません!
まずは、環境変数を格納しておくYAMLファイルを作成します。
vim config/settings.yml
中身はこんな感じで config/settings.yml
defaults: &defaults
email: dev@example.com
secret: foo123
development:
<<: *defaults
test:
<<: *defaults
email: test@example.com
production:
<<: *defaults
email: info@example.com
secret: 321oof
そしてgit管理下から外します。 vim .gitignore
.gitignore config/settings.yml
あとはこれをRailsアプリケーションが初期化される前に読み込みます。
vim config/application.rb
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
#ここで先ほど生成したymlファイルを読み込んで環境変数として使用します。
ENV.update YAML.load_file('config/settings.yml')[Rails.env] rescue {}
module SomeApp
class Application < Rails::Application
あとはお好きな場所で環境変数として呼び出せば、自由に設定変数を使えます。
app/models/somemodel.rb
puts ENV['email']
#=> secret
config/produciton.rb
puts ENV['secret']
#=> 321 oof
個人的には、config/production.rb
の中でパスワードなどの設定情報を書き込まなければいけなくなった際に使いました。
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
# smtpサーバのアドレス
:address => ENV['sakura_address'],
:port => 587,
# tmtpサーバにアクセスするためのユーザ名
:user_name => ENV['sakura_user_name'],
# ユーザ名に対するパスワード
:password => ENV['sakura_password'],
:domain => 'example.com',
:authentication => :plain,
:enable_starttls_auto => false
}
参考になれば幸いです。
問題は、バージョン管理を行っていないので、ふとした瞬間に設定ファイルを消してしまい炎上すること ぐらいです() もっと効率的な設定ファイルの管理方法があればご教授ください。
参考情報