【问题标题】:boto3 wait_until_running doesn't work as desiredboto3 wait_until_running 无法按预期工作
【发布时间】:2020-12-01 18:19:30
【问题描述】:

我正在尝试使用 boto3 编写一个脚本来启动一个实例并等待它启动。根据 wait_until_running 的文档,它应该等到实例完全启动(我假设检查应该没问题)但不幸的是它只适用于 wait_until_stopped 并且在 wait_until_running 的情况下它只是启动实例并且不等到它完全开始。不知道我在这里做错了什么还是这是boto3的错误。

代码如下:

import boto3


ec2 = boto3.resource('ec2',region_name="ap-southeast-2")
ec2_id = 'i-xxxxxxxx'
instance = ec2.Instance(id=ec2_id)
print("starting instance " + ec2_id)
instance.start()
instance.wait_until_running()
print("instance started")

【问题讨论】:

  • 服务员只等到状态变为running以下:pendingrunningshutting-downterminatedstoppingstopped。跨度>
  • wait_until_running() 应该等到实例的状态更改为 running。它不会等到操作系统完全启动,并且所有服务都已启动等。这就是我假设您说“完全启动”时的意思。
  • Thaks @MarkB,我只是想设置几秒钟的睡眠间隔并检查直到端口 22 可以访问(确保实例最终启动)。这是一个好方法还是有其他更好的 AWS 方法来完成这项工作。

标签: python amazon-web-services boto3


【解决方案1】:

感谢@Mark B@Madhurya Gandi,这是适用于我的解决方案:

import boto3,socket
retries = 10
retry_delay=10
retry_count = 0
ec2 = boto3.resource('ec2',region_name="ap-southeast-2")
ec2_id = 'i-xxxxxxxx'
instance = ec2.Instance(id=ec2_id)
print("starting instance " + ec2_id)
instance.start()
instance.wait_until_running()
while retry_count <= retries:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((instance.public_ip_address,22))
    if result == 0:
        Print "Instance is UP & accessible on port 22, the IP address is:  ",instance.public_ip_address
        break
    else:
        print "instance is still down retrying . . . "
        time.sleep(retry_delay)
   except ClientError as e:
       print('Error', e)

【讨论】:

  • 您的格式可能弄乱了代码示例 - 大写 P 的“打印”不起作用,您的 except ClientError 语句对我不起作用。
【解决方案2】:

我已经尝试过 instance.wait_until_running()。将实例更新为运行状态需要时间。根据亚马逊文档link,它表示实例至少需要 60 秒才能启动。这是一个对我有用的示例代码。希望对您有所帮助!

;创建5个实例

ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)
time.sleep(60)

;打印你的实例

【讨论】:

  • 谢谢,我就是这么做的 :) 看起来这是解决这个问题的唯一方法。
猜你喜欢
  • 2020-01-21
  • 2013-12-23
  • 2014-12-09
  • 2016-01-13
  • 2020-09-21
  • 2011-08-17
  • 2012-04-29
  • 2021-08-12
  • 2019-02-04
相关资源
最近更新 更多