Dr Nic

Capistrano variables

Here’s an example of how you can pass variables to your capistrano actions via the cap command.

So, the above action could be called as follows:

cap log
cap log -s lines=1000
cap log -s rails_env=test

For reference, you pass values to Rake tasks via environment variables:

rake db:migrate RAILS_ENV=test

Inside the db:migrate task, you’d retrieve the value ‘test’ via ENV['RAILS_ENV'].

And further more, this then compares to how you'd normally pass option values into normal command-line apps:

tail -n 1000 log/production.log

Who said the unix command line wasn't easy peasy. Bah.

Related posts:

  1. Magic Multi-Connections: A “facility in Rails to talk to more than one database at a time” At this point in time there’s no facility in Rails...

10 Responses to “Capistrano variables”

  1. atmos says:

    Nice! I hadn’t used that before.

  2. topfunky says:

    Actually, you don’t even need the configuration.variables part! It’s almost as magic as Dr. Nic’s models.

    Anything passed with dash-s becomes a local variable in your Capistrano recipes.

  3. Dr Nic says:

    @topfunky – that’s how I thought it should work too. But it wasn’t working, hence hunting down configuration.variables hash.

    Here’s the same action using local variables:

    task :log do
      lines ||= 100
      rails_env ||= 'production'
      # lines     = configuration.variables[:lines] || 100
      # rails_env = configuration.variables[:rails_env] || 'production'
      env   = ENV['RAILS_ENV'] || 'production'
      run "tail -n #{lines} #{deploy_to}/#{shared_dir}/log/#{rails_env}.log" do |ch, stream, out|
        puts out
      end
    end
    

    But when I run cap log -s lines=10 it still looks for the default 100.

    I’ll ping it to the capistrano mailing list/Jamis and see if anyone can reproduce this.

  4. choonkeat says:

    I have a “ask” method in my capistrano instead: http://pastie.caboo.se/52993

    So I’ll do

    ask :server_port, "Port number", "3000"
    puts server_port

    If the value is given at command line via -S server_port=5000 then it won’t ask, otherwise prompt.

  5. Very useful!

    This is a good capistrano variables example and also a very useful recipe!

    I’ve started using this recipe and blogged it in spanish at my blog: http://spejman.blogspot.com/2007/04/logs-del-servidor-con-capistrano.html

    Thanks for your post!

  6. Dr Nic says:

    @all – see http://groups.google.com/group/capistrano/browse_thread/thread/d4d30393b6f41605 for discussion about the mysterious #lines variable/method.

  7. topfunky says:

    In Cap2 this appears to be just ‘variables’ instead of ‘configuration.variables’.

  8. sesli sohbet says:

    In Cap2 this appears to be just ‘variables’ instead of ‘configuration.variables’.

  9. Alexander says:

    Thank you for this tip.
    I needed it for deploying sinatra app. I have to set remote RACK_ENV variable when deploying.

    Saved my time!