简体   繁体   中英

How to check instance state use “aws-sdk” in ruby?

I have created an instance using run_instances method on EC2 client. I want to check for whether instance is running or not. One way to do is use describe_instances method and parse the response object. I want to keep checking for instance state periodically till the instance state is :running . Anybody knows how to do that? Is there any simpler way rather than parsing the response object? (I can't use fog gem since it does not allow me to create instances in a VPC)

The v2 aws-sdk gem ships with waiters. These allow you to safely poll for a resource to enter a desired state. They have sensible limits and will stop waiting after a while raising a waiter failed error. You can do this using the resource interface of the v2 SDK 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])

wait_until methods are definitely better than checking statuses on yourself.

But just in case you want to see instance status:

#!/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

here is something to start with:

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

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