EC2:等待新实例处于运行状态

时间:2013-09-27 15:05:10

标签: amazon-ec2

我想基于我存储的AMI创建一个新实例。

我通过以下代码实现此目的:

RunInstancesRequest rir = new RunInstancesRequest(imageId,1, 1);
// Code for configuring the settings of the new instance
...
RunInstancesResult runResult = ec2.runInstances(rir);

但是,我找不到等待“阻塞”/等待,直到实例启动并运行Thread.currentThread()。sleep(xxxx)命令。

另一方面,StartInstancesResult和TerminateInstancesResult为您提供了一种访问实例状态并能够监视任何更改的方法。但是,一个全新的实例的状态怎么样?

6 个答案:

答案 0 :(得分:22)

boto3有:

instance.wait_until_running()

答案 1 :(得分:10)

来自AWS CLI changelog for v1.6.0

  

添加一个wait子命令,允许命令阻止直到AWS   资源达到给定状态(issue 992issue 985

我没有在文档中看到这一点,但以下内容对我有用:

aws ec2 start-instances --instance-ids "i-XXXXXXXX"
aws ec2 wait instance-running --instance-ids "i-XXXXXXXX"

在EC2实例运行之前,wait instance-running行没有完成。

我不使用Python / boto / botocore,但假设它有类似的东西。查看waiter.py on Github

答案 2 :(得分:5)

等待EC2实例准备就绪是一种常见模式。在Python库中,您还可以使用sleep调用解决此问题:

   reservation = conn.run_instances([Instance configuration here])
   instance = reservation.instances[0]

   while instance.state != 'running':
       print '...instance is %s' % instance.state
       time.sleep(10)
       instance.update()

使用此机制,您可以在新实例出现时进行轮询。

答案 3 :(得分:2)

根据您尝试执行的操作(以及计划启动的服务器数量),您可以在AMI上安装一个简单的程序/脚本,该程序/脚本在实例启动时运行一次,而不是您计划启动的服务器数量。发出通知,即向AWS SNS主题发送通知。

然后,需要了解新服务器启动的进程可以订阅此SNS主题,并且每次服务器启动时都会收到推送通知。

从不同的角度解决同样的问题;你的里程可能会有所不同。

答案 4 :(得分:0)

答案 5 :(得分:0)