Last Updated: May 17, 2017
· scosta

Running a Rake task during a Rails 4 deployment using Capistrano 3

There seem to a be lot of different ways posted online to get a Rake task to run during a Rails deployment using Capistrano 3.

This is what worked for me, and I think it's cleaner than a lot of the solutions i saw posted on SO or similar.

Let's say you have a Rake task that locally you can run with rake system:update_rules. Then a you would want to add the following to your deploy.rb:

namespace :system do
  desc 'Update the system rules '
  task :update_rules do
    on roles(:all) do
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute :rake, 'system:update_rules'

Then at the top of your deploy.rb put:

after 'deploy:published', 'system:update_rules'

This will run after the deployment has finished everything else which ensures that and changes you've made to your application will be reflected when Capistrano executes the task.