简体   繁体   English

如何检查实例状态在ruby中使用“aws-sdk”?

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

I have created an instance using run_instances method on EC2 client. 我在EC2客户端上使用run_instances方法创建了一个实例。 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. 一种方法是使用describe_instances方法并解析响应对象。 I want to keep checking for instance state periodically till the instance state is :running . 我想定期检查实例状态,直到实例状态为: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) (我不能使用fog宝石,因为它不允许我在VPC中创建实例)

The v2 aws-sdk gem ships with waiters. v2 aws-sdk宝石带有服务员。 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: 您可以使用v2 SDK的资源接口或使用客户端界面执行此操作:

# 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. wait_until方法肯定比检查自己的状态更好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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