プログラマでありたい

おっさんになっても、プログラマでありつづけたい

今更聞けないCapistranoでリリースの自動化

 ここ数年で開発の現場でAgile開発の文化や手法が、ずいぶんと取り入れられるようになってきているようです。アジャイル開発はその根底に文化が大事ですが、それを支えるツールというのも重要になってきます。ソース管理やビルド管理、テストの自動化と色々ありますが、今回はリリースの自動化のお話です。その中で主にRails使われることが多いCapistranoの設定と使い方です。

環境の説明

・Ruby 1.9
・Rails 3.2
・Passenger
・Git
・SQLite3

目指す構成

 今回は単純化する為に、1サーバの中にGitのリポジトリもApache+PassengerもDBも入れておきます。また複数の環境(開発、ステージング、本番)にデプロイ出来るように、それぞれの構成を別けて記述するようにします。(capistrano-extを使用)

設定

必要モジュールのインストール

$gem install capistrano
$gem install capistrano-ext
$gem install capistrano_colors

また、Gemfileの中に追記しておくと良いと思います。

$ vi Gemfile
group :deployment do
  gem 'capistrano'
  gem 'capistrano-ext'
  gem 'capistrano_colors'
end
$ bundle install


サンプルのプロジェクトの作成

$ rails new capistrano-sample
$ cd capistrano-sample
$ rails g model item name:string price:integer
$ rails g controller items recent
$ git init
$ git add .
$ git commit -m "initial import"


capistranoのひな形ファイルの作成

$ capify .
[add] writing './Capfile'
[add] writing './config/deploy.rb'
[done] capified!


ひな形を元に編集

vi config/deploy.rb

基本方針として、共通設定をconfig/deploy.rbに記述します。
環境ごとの差分をconfig/deploy/環境名.rbに記述します。
config/deploy.rb
/deploy/development.rb
/staging.rb
/production.rb


変更箇所は、次のような感じです。
deploy.rb

require 'capistrano/ext/multistage'

set :application, "capistrano sample"

# リポジトリの設定
set :repository,  "git+ssh://localhost/path/to/develop/capistrano-sample"
set :scm, :git

# RVMを利用時の設定
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require 'rvm/capistrano'
set :rvm_ruby_string, '1.9.3'
set :rvm_type, :user

# ユーザの設定
set :user, 'username'
set :use_sudo, false 
default_run_options[:pty] = true

def restart_file
  File.join(current_path, 'tmp', 'restart.txt')
end

namespace :deploy do
  task :restart, :roles => :app do
    run "touch #{restart_file}"
  end
end


deplpy/development.rb

set :rails_env, 'development'

role :web, "localhost"
role :app, "localhost"
role :db,  "localhost", :primary => true

set :deploy_to, '/var/www/capistrano_sample/development/' 

deploy/production.rb

set :rails_env, 'production'

role :web, "localhost"
role :app, "localhost"
role :db,  "localhost", :primary => true

set :deploy_to, '/var/www/capistrano_sample/production/' 

デプロイ

開発環境にデプロイ

$ cap development deploy:setup
$ cap development deploy:cold


本番環境にデプロイ

$ cap production deploy:setup
$ cap production deploy:cold


コマンド一覧

$ cap -T
cap bundle:install        # Install the current Bundler environment.
cap deploy                # Deploys your project.
cap deploy:check          # Test deployment dependencies.
cap deploy:cleanup        # Clean up old releases.
cap deploy:cold           # Deploys and starts a `cold' application.
cap deploy:create_symlink # Updates the symlink to the most recently deployed...
cap deploy:migrate        # Run the migrate rake task.
cap deploy:migrations     # Deploy and run pending migrations.
cap deploy:pending        # Displays the commits since your last deploy.
cap deploy:pending:diff   # Displays the `diff' since your last deploy.
cap deploy:rollback       # Rolls back to a previous version and restarts.
cap deploy:rollback:code  # Rolls back to the previously deployed version.
cap deploy:setup          # Prepares one or more servers for deployment.
cap deploy:start          # Blank task exists as a hook into which to install...
cap deploy:stop           # Blank task exists as a hook into which to install...
cap deploy:symlink        # Deprecated API.
cap deploy:update         # Copies your project and updates the symlink.
cap deploy:update_code    # Copies your project to the remote servers.
cap deploy:upload         # Copy files to the currently deployed version.
cap deploy:web:disable    # Present a maintenance page to visitors.
cap deploy:web:enable     # Makes the application web-accessible again.
cap development           # Set the target stage to `development'.
cap invoke                # Invoke a single command on the remote servers.
cap multistage:prepare    # Stub out the staging config files.
cap production            # Set the target stage to `production'.
cap shell                 # Begin an interactive Capistrano session.

Some tasks were not listed, either because they have no description,
or because they are only used internally by other tasks. To see all
tasks, type `cap -vT'.

Extended help may be available for these tasks.
Type `cap -e taskname' to view it.


 今回の構成では、同一サーバに開発・本番環境とパスを別けていました。実際のプロジェクトでは、role :web,:app,:db等で別のサーバを指定してください。DBの部分も、rakeのmigrateの設定をちゃんと記述していれば問題ないです。
 
See Also:
Capistranoのタスク一覧
ChefとCapistranoの素敵な関係。或いはレイヤーの違いの話


参考:
Capistrano 実践Tips集
さくらVPS Capistrano編 - プログラミングノート
Capistranoとcapistrano-ext - 祈れ、そして働け 〜 Ora et labora