使っているのはこんな環境です。
- HerokuにRailsのProductionとStaging環境がある。
- Stagingで任意のブランチを動かしたいことがある。
今までHerokuにデプロイする時はこうしてましたが、
$ git push prod master
今後はこのようになりました。
$ bundle exec rake deploy:prod
Dryrunも出来ます。
$ bundle exec rake deploy:prod DRYRUN=1
Stagingで任意のブランチを動かしたい時はこちら。
$ bundle exec rake deploy:staging BRANCH=<any-branch>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :deploy do | |
nowrite ENV['DRYRUN'] | |
desc 'Deploy to production server' | |
task :prod do | |
before_last_release = last_release :prod | |
sh 'git push prod master' | |
after_last_release = last_release :prod | |
unless before_last_release == after_last_release | |
notify_to_chatwork :prod, before_last_release, after_last_release | |
end | |
end | |
desc 'Deploy to staging server' | |
task :staging do | |
before_last_release = last_release :staging | |
branch = ENV['BRANCH'] | |
if branch | |
sh "git push staging #{branch}" | |
sh "git push -f staging #{branch}:master" | |
else | |
sh 'git push staging master' | |
end | |
after_last_release = last_release :staging | |
unless before_last_release == after_last_release | |
notify_to_chatwork :staging, before_last_release, after_last_release | |
end | |
end | |
def last_release stage | |
return { deploy_version: nil, commit_hash: nil } if nowrite | |
deploy_version = nil | |
commit_hash = nil | |
`heroku releases --app=#{heroku_app_name stage}`.each_line do |line| | |
if line =~ /^(v\d+) +Deploy ([a-f\d]+) / | |
deploy_version = $1 | |
commit_hash = $2 | |
break | |
end | |
end | |
{ deploy_version: deploy_version, commit_hash: commit_hash } | |
end | |
def heroku_app_name stage | |
stage == :prod ? '<Heroku prod app name>' : '<Heroku staging app name>' | |
end | |
def notify_to_chatwork stage, before_last_release, after_last_release | |
room_id = stage == :prod ? '<Production room_id>' : '<Staging room_id>' | |
user_name = `git config user.name`.chomp | |
after_deploy_version = after_last_release[:deploy_version] | |
url = "<Your GitHub URL>/compare/#{before_last_release[:commit_hash]}...#{after_last_release[:commit_hash]}" | |
ChatWork.api_key = '<Your API Key>' | |
ChatWork::Message.create room_id: room_id, body: "#{user_name} deployed #{after_deploy_version} #{url}" | |
end | |
end |
Gistのページ にも補足情報を書きました。
皆さん、Herokuへのデプロイはどんな方法でやってます?
See also
ChatWorkのAPIを叩けるGemをつくった - 良いあそなすちゃん
チャットワークAPIを限定プレビュー公開します!|ChatWorkブログ
追記(2014-01-24):
なぜかデプロイ後のHashが更新されないことがあったので、
git ls-remote prod
の代わりにheroku release
を使うようにしました。
なんだかコードが長くなってしまったorz