How do I run a rake task from Capistrano?

2020-01-25 04:00发布

I already have a deploy.rb that can deploy my app on my production server.

My app contains a custom rake task (a .rake file in the lib/tasks directory).

I'd like to create a cap task that will remotely run that rake task.

16条回答
该账号已被封号
2楼-- · 2020-01-25 04:01

...couple of years later...

Have a look at capistrano's rails plugin, you can see at https://github.com/capistrano/rails/blob/master/lib/capistrano/tasks/migrations.rake#L5-L14 it can look something like:

desc 'Runs rake db:migrate if migrations are set'
task :migrate => [:set_rails_env] do
  on primary fetch(:migration_role) do
    within release_path do
      with rails_env: fetch(:rails_env) do
        execute :rake, "db:migrate"
      end
    end
  end
end
查看更多
我命由我不由天
3楼-- · 2020-01-25 04:01

This worked for me:

task :invoke, :command do |task, args|
  on roles(:app) do
    within current_path do
      with rails_env: fetch(:rails_env) do
        execute :rake, args[:command]
      end
    end
  end
end

Then simply run cap production "invoke[task_name]"

查看更多
乱世女痞
4楼-- · 2020-01-25 04:02

Previous answers didn't help me and i found this: From http://kenglish.co/run-rake-tasks-on-the-server-with-capistrano-3-and-rbenv/

namespace :deploy do
  # ....
  # @example
  #   bundle exec cap uat deploy:invoke task=users:update_defaults
  desc 'Invoke rake task on the server'
  task :invoke do
    fail 'no task provided' unless ENV['task']

    on roles(:app) do
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute :rake, ENV['task']
        end
      end
    end
  end

end

to run your task use

bundle exec cap uat deploy:invoke task=users:update_defaults

Maybe it will be useful for someone

查看更多
做个烂人
5楼-- · 2020-01-25 04:05
run("cd #{deploy_to}/current && /usr/bin/env rake `<task_name>` RAILS_ENV=production")

Found it with Google -- http://ananelson.com/said/on/2007/12/30/remote-rake-tasks-with-capistrano/

The RAILS_ENV=production was a gotcha -- I didn't think of it at first and couldn't figure out why the task wasn't doing anything.

查看更多
疯言疯语
6楼-- · 2020-01-25 04:06

Use the capistrano-rake gem

Just install the gem without messing with custom capistrano recipes and execute desired rake tasks on remote servers like this:

cap production invoke:rake TASK=my:rake_task

Full Disclosure: I wrote it

查看更多
smile是对你的礼貌
7楼-- · 2020-01-25 04:06

Here's what I put in my deploy.rb to simplify running rake tasks. It's a simple wrapper around capistrano's run() method.

def rake(cmd, options={}, &block)
  command = "cd #{current_release} && /usr/bin/env bundle exec rake #{cmd} RAILS_ENV=#{rails_env}"
  run(command, options, &block)
end

Then I just run any rake task like so:

rake 'app:compile:jammit'
查看更多
登录 后发表回答