简体   繁体   中英

Create ec2 instance with ruby and connect to the created machine

After i create the instance using instances.create, i need to connect to the machine and perform some operations. The question is - what is the best way to know that the creation has finished and i can connect to the machine ?

The machine's state right after creating it is 'running', so how can i know when the machine finished its initialization and i can ssh to it ?

I saw an existing code where its done by ssh'ing every X seconds, and if its get timeout than it means that the machine is still initializing.

I am looking for a more elegant way.

Once the instance is created, you get the instances ID. So, use that instance ID to check the "Instance Status" . Each instance has to go through 2 status checks : System Status Check and Instance Status Check.

I have observed that once both these checks are passed, the instance is ready to be logged in.

The corresponding Method in ruby sdk which pulls this data is describe_instance_status

I was also looking for a similar solution, and I found a test on the AWS Ruby SDK that does just that: https://github.com/aws/aws-sdk-ruby/blob/master/samples/ec2/run_instance.rb

begin
  Net::SSH.start(instance.ip_address, "ec2-user",
                 :key_data => [key_pair.private_key]) do |ssh|
  puts "Running 'uname -a' on the instance yields:"
  puts ssh.exec!("uname -a")
end
rescue SystemCallError, Timeout::Error => e
  # port 22 might not be available immediately after the instance finished
  launching
  sleep 1
  retry
end

It might not be the cleanest solution, but it's a solution Amazon adopts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM