Last Updated: September 30, 2021
·
25.24K
· tacionery

Writing Custom Tasks for Capistrano 3

Capistrano is a great Ruby Gem to automate Deploys. Lets create a task to run some database commands on a VPS.


I'll assume that you have capistrano 3 already installed in your Rails application.
Before we create the task, let's see if your Capfile imports rake or cap tasks files. Open it and check if you have this line:

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

It's importing rake tasks files, but you may also import .cap rake files as well.
So, let's create a file called db_tasks.rake into lib/capistrano/tasks directory.

namespace :custom do
  desc 'run some rake db task'
  task :run_db_task do
    on roles(:app) do
      within "#{current_path}" do
        with rails_env: "#{fetch(:stage)}" do
          execute :rake, "db:create"
        end
      end
    end
  end
end

To run this task, open the terminal, go to application directory and run the command below: </br>

$ cap production custom:run_db_task

It will run the rake:db_create task within the deployed rails application directory with the given stage, in this case, production.


Ok. But... What if I want to pass a parameter to my task? Let's rewrite our task to accept parameters that will come from the terminal.

namespace :custom do
  desc 'run some rake db task with params'
  task :run_db_task, :param do
    on roles(:app) do
      within "#{current_path}" do
        with rails_env: "#{fetch(:stage)}" do
          execute :rake, args[:param]
        end
      end
    end
  end
end

Now let's run this task on the terminal: <br>

$ cap production custom:run_db_task[db:setup]

So, that's it. That's how to create custom task for capistrano 3 with parameters.


For more information about Capistrano, just check the link bellow: <br>

http://capistranorb.com/

Hope you've liked it. I'll try to write more stuff about capistrano soon.

1 Response
Add your response

So I have a task to run migrations, but for some reason I keep getting an error that the method "within" is undefined....

Any idea what I might be missing? I'm no hero at Ruby, but this looks like something native rather then a forgotten include or require....

over 1 year ago ·