Skip to content

Instantly share code, notes, and snippets.

@ilyazub ilyazub/rake_ssh_deploy.md
Last active Aug 29, 2015

Embed
What would you like to do?
Rake SSH deployment

Rake SSH deployment

Usage

Set up deployment folder

bundle exec rake deploy:setup

Update code and restart server

bundle exec rake deploy

Update code

bundle exec rake deploy:update_code

Restart server

bundle exec rake deploy:restart_server

Notes

Assuming you'll use rbenv on remote server. Change path to gem executable files if you'll use something else.

Sourcing ~/.profile on remote machine before command execution to load environment variables. Check StackOverflow question to understand why to do it this way (there should be a better approach).

desc 'Deploy and restart server'
task deploy: [
'deploy:update_code',
'deploy:restart'
]
namespace :deploy do
@user = 'username'
@host = 'www.example.com'
@repository = 'git@github.com:owner/repository.git'
@branch = 'origin/master'
@deployment_path = '/path/to/directory'
desc 'Setup folder'
task :setup do
remote_task(create_folder_if_not_exists)
end
desc 'Update code'
task :update_code do
remote_task([
update_code_command,
bundle_install_command
])
end
desc 'Restart server'
task :restart do
remote_task(restart_server_command)
end
def remote_task(commands, options = {})
commands = Array(commands)
commands.each do |command|
sh "ssh #{@user}@#{@host} \"#{source_profile} && #{change_dir} && #{command}\""
end
end
def source_profile
"source /home/#{@user}/.profile"
end
def change_dir
"cd #{@deployment_path}"
end
def create_folder_if_not_exists
"mkdir -p #{@deployment_path}"
end
def update_code_command
[
"git fetch origin",
"git reset --hard #{@branch}"
].join(" && ")
end
def bundle_install_command
"/home/#{@user}/.rbenv/shims/bundle install --without development test"
end
def restart_server_command
[
"/home/#{@user}/.rbenv/shims/bundle exec rake app:kill",
"/home/#{@user}/.rbenv/shims/bundle exec rackup -D"
].join(" && ")
end
end
namespace :app do
desc "Kill rackup daemon" # Taken from StackOverflow (http://stackoverflow.com/a/10747618/1291371)
task :kill do
pid_file = File.expand_path('../tmp/pids/rackup.pid', __FILE__)
if File.exist?(pid_file)
pid = File.read(pid_file).to_i
Process.kill 9, pid
File.delete pid_file
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.