LoginSignup
4
3

More than 5 years have passed since last update.

[Ruby on Rails] 複数のステージング環境を用意する

Last updated at Posted at 2018-07-04

環境

  • Rails 5.0
  • Ruby 2.3.3
  • AWS

背景

現在のチームの開発の流れ:

development -> staging -> production

開発チームメンバーが増えると開発のスピードを上げるために、複数のステージング環境が望ましくなってきました。それで複数のステージング環境を構築してみました。

現在のステージング(stagig)を除いで、2つ別のステージング環境(staging1, staging2)を作りました。

方針

名前 説明
Web Server 新しいインスタンを新規追加
DB 別のDB名にして、同じStaging RDS Instanceに新規作成
Redis 同じReids Instanceの別のDBを使う

Ec2 Instance

用意

Terraformで2つの同じステージングインスタントを追加した。

設定

InstanceのタグStagesをstaging1/staging2に設定します(デプロイのため)。

Database

用意

そんなに使われないので、同じRDS Instanceに複数のDBを作りました。

mysqldump -h hostname -u username -p password --single-transaction pro_staging > dump.sql

mysql -h hostname -u username -p password --single-transaction pro_staging_1 < dump.sql
mysql -h hostname -u username -p password --single-transaction pro_staging_2 < dump.sql

設定

現在の3環境(development, staging, production)を増やすつもりなく、ステージング環境そのまま利用します。

database.ymlにはすでにdotenvで環境変数を入れてますので、修正が不要です。

database.yml
staging:
  <<: *default
  pool: 20
  database: <%= ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_USERNAME'] %>
  password: <%= ENV['DATABASE_PASSWD'] %>
  host:     <%= ENV['DATABASE_HOST'] %>

dotenvのファイルを増やして、.env.staging1と.env.staging2を追加する。

.env.staging1
# RDS
DATABASE_NAME = pro_staging_1 # or pro_staging_2
DATABASE_USERNAME = xxx
DATABASE_PASSWD = xxx
DATABASE_HOST = xxx

Redis

用意

そんなに使われないので、同じRedis Instanceに別のDBを使います。defaultは0を使ってるので、staging_1とstaging_2はDB 1と2を使ってもらいます。

設定

config/environments/staging.rb
config.cache_store = :redis_store, ENV['REDIS_ENDPOINT'], { expires_in: 12.hours }
.env.staging1
# Redis
REDIS_ENDPOINT=redis://xxx:6379/1

Rails

設定

Staing1とStaing2はstaging環境としてうごくように設定します。

config//environment.rb
Rails.env = 'staging' if Rails.env =~ /staging\d+/

Capistrano

cap-ec2を使って、デプロイしてます。

設定

  • デプロイstagesを追加する
config/deploy.rb
set :stages, %w[development staging staging1 staging2 production]
  • .envファイルのコピータスク修正
config/deploy.rb
desc 'set env file'
  task :set_env_file do
    on roles(:app) do
      with rails_env: fetch(:rails_env) do
        case fetch(:stage)
        when :staging1
          p 'copy .env.staging1'
          upload!('.env.staging1', "#{shared_path}/pro/.env.staging")
        when :staging2
          p 'copy .env.staging2'
          upload!('.env.staging2', "#{shared_path}/pro/.env.staging")
      end
    end
  end
  • 新しいstageの作成

同じソースを増やしたくないので、symbolic link fileを使います。

ln -s config/depoly/staging.rb config/depoly/staging1.rb
ln -s config/depoly/staging.rb config/depoly/staging2.rb

これて2つのステージング環境を追加することができました。時々本番とのデータsyncが必要になります。

4
3
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
4
3