ruby-on-railsrubyrakecapistranocapistrano3

Run rake task from Capistrano if it exists


I need to a create a Capistrano pre-deploy step that runs a custom rake task.

in deploy.rb:

before 'deploy:starting', 'db:rollback_staging'

namespace :db do
  desc 'Rollback staging db only if PR already deployed requires rollback'
  task :rollback_staging do
    on roles(:master) do
      within current_path.to_s do
        with rails_env: 'staging' do
          execute :rake, 'release:rollback_staging'
        end
      end
    end
  end
end

The problem is that when deploying this code the rake task is not yet present on the server and therefore deploy fails with:

rake stdout: rake aborted!

Don't know how to build task 'release:rollback_staging' (See the list of available tasks with `rake --tasks`)

If there a way to check if the rake task exists from Capistrano? smth like:

with rails_env: 'staging' do
  execute :rake, 'release:rollback_staging' if rake_exists? 'release:rollback_staging'
end

Solution

  • I ended up just ignoring not 0 exit code from a rake task using raise_on_non_zero_exit: false:

    with rails_env: 'staging' do
      execute :rake, 'release:rollback_staging', raise_on_non_zero_exit: false
    end