Capturing Output in Capistrano

Posted by Jonathan

A common question about Capistrano tasks is how to capture the output of a task. By default Capistrano will just execute your command and ignore any output.

But sometimes you want to capture and log the output. There is no easy command to do this right now, you have to use the SSH channels:

run "cat /etc/passwd " do |ch, stream, data|
  if stream == :err
    logger.debug "capured output on STDERR: #{data}"
  else # stream == :out
    logger.debug "capured output on STDOUT: #{data}"
  end
end

You can even send data back depending on the captured output:

run "mysql -u root my_database -p < /tmp/dump.sql" do |ch, stream, data|
  if data =~ /password:/
    ch.send_data(root_password)
  end
end

Using this technique you can store command output in the Webistrano log or just print it if you are using stock Capistrano.

Comments

Leave a response

  1. Ryan DavisSeptember 30, 2007 @ 10:15 PM

    One more thing I found confusing… that’s why vlad makes it easy:

    `passwd = run(“cat /etc/passwd”)`