Are you usually deploying your Ruby applications with Capistrano and want to run remote commands depending on the server IP?

A not very well documented trick is to interpolate the special string $CAPISTRANO:HOST$ on your command. For example:

server_ip = capture("echo $CAPISTRANO:HOST$").strip
run "I'm running on server #{server_ip}"

The problem comes when you’re deploying to multiple servers, like this:

role :app, '192.168.1.1', '192.168.1.2'

task :some_task, :role => :app do
  server_ip = capture("echo $CAPISTRANO:HOST$").strip
  run "I'm running on server #{server_ip}"
end

This will always print your app’s role first ip, 192.168.1.1.

The solution is even less documented:

role :app, '192.168.1.1', '192.168.1.2'

task :some_task, :role => :app do
  find_servers_for_task(current_task).each do |current_server|
    run "I'm running on server #{current_server.host}"
  end
end

You know that ruby hype which claims “no need to document things, simply read the code”… well, that’s the reason for blog posts like this one. A mess.