Search code examples
ruby-on-railsnet-sshresque

Net::SSH connection fails from inside resque job


I have an app that sets creates EC2 instances - I have a resque task that will configure the server (via ssh) once it's up and running:

    Net::SSH.start(server.dns_name, 'root', :keys => ['~/.ssh/testkey.pem'], :paranoid => false, :verbose => :debug) do |ssh|
         result = ssh.exec!("ls -l")
         puts result
    end

I get an error:

*** (Job{serverbuild} | ServerBuilder | [22]) failed: #<Errno::ECONNREFUSED: Connection refused - connect(2)>

If I run this from irb, or from my rails app, it's connects just fine. Any thoughts?


Solution

  • It's a timing issue - EC2 instances are "up" before the will accept ssh requests. I rescued the error retried again in 20 seconds (up to 5 times). working now.

      begin
         Net::SSH.start(server.dns_name.to_s, 'root', :keys => ['/Users/stevebrewer/.ssh/testkey.pem'], :paranoid => false) do |ssh|
           result = ssh.exec!("ls -la")
           puts result
         end
      rescue
         if(retries < 5)
           Resque.enqueue_at(20.seconds.from_now, ServerBuilder, server_id, retries + 1)
         end
      end