Read more

Capistrano: Doing things on rollback

Dominik Schöler
July 04, 2017Software engineer at makandra GmbH

Capistrano has the concept of a "rollback" that comes in really handy in case of errors. When you notice that your recent deploy was faulty, run cap deploy:rollback and you're back with the previous release. In case of an error during a deployment, Capistrano will rollback itself.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

But, you may ask, how can it know how to revert all the custom stuff I'm doing during deployment? It can't. But you can tell it how to.

Capistrano 3 Show archive.org snapshot

Deploy and rollback are nearly identical, just some tasks are replaced:

deploy:updating → deploy:reverting
deploy:updated → deploy:reverted
deploy:finishing → deploy:finishing_rollback

Simply hook your custom rollback tasks to the respective Capistrano tasks.

Capistrano 2 Show archive.org snapshot

In your custom deploy task, use #on_rollback to define what needs to happen during a rollback. Example:

namespace :slack do
  task :starting do
    on_rollback { slack.failed }
    slack_connect 'Deploy started'
  end

  task :failed do
    slack_connect 'Deploy failed'
  end
end

Note that there is a hidden requirement for on_rollback: it must be run inside a Capistrano transaction. Don't worry if you've never heard of this. As long as your custom task is hooked into the deploy task, it will work because deploy internally opens a transaction.

Posted by Dominik Schöler to makandra dev (2017-07-04 09:17)