How can I check the usage status of an instance of "aws-sdk" in ruby?

I created an instance using the method run_instances

for the EC2 client. I want to check if an instance is running or not. One way to do it is to use a method describe_instances

and parse the response object. I want to periodically check the state of the instance until the state of the instance is there :running

. Does anyone know how to do this? Is there an easier way than parsing the response object? (I cannot use the fog

gem as it does not allow me to instantiate in the VPC)

+3


source to share


3 answers


Driver v2 aws-sdk

comes with waiters. This allows you to safely poll the resource to enter the desired state. They have reasonable limits and will stop waiting after a while if the waiter's error is not reached. You can do this using the v2 SDK resource interface or using the client interface:



# resources
ec2 = Aws::EC2::Resource.new
ec2.instance(id).wait_until_running

# client
ec2 = Aws::EC2::Client.new
ec2.wait_until(:instance_running, instance_ids:[id])

      

+3


source


wait_until

methods are definitely better than checking statuses on yourself.

But just in case you want to see the status of the instance:



#!/usr/bin/env ruby

require 'aws-sdk'

Aws.config.update({
  region: 'us-east-1',
  credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY'], ENV['AWS_SECRET_KEY'])
})

ec2 = Aws::EC2::Client.new

instance_id = 'i-xxxxxxxx'

puts ec2.describe_instance_status({instance_ids: [instance_id]}).instance_statuses[0].instance_state.name

      

+1


source


here's where to start:

i = ec2.instances[instance_id]
i.status
while i.status != :running
 sleep 5
end

      

-1


source







All Articles