Boto3 get_waiter 不会正确停止和启动实例

Posted

技术标签:

【中文标题】Boto3 get_waiter 不会正确停止和启动实例【英文标题】:Boto3 get_waiter does not stop and start instance correctly 【发布时间】:2022-01-21 09:59:32 【问题描述】:

问题: 您好,我正在尝试在同一个 lambda 函数中停止和启动实例。我正在使用服务员,但是上面的代码只会停止实例,但不会启动它,因为它不会等待停止。请帮我更正代码,谢谢

代码:

import boto3
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
  
    ids = ['i-xxxx']

    #stop Instance
    ec2.stop_instances(InstanceIds=ids)
    waiter = ec2.get_waiter('instance_stopped')
    waiter.wait(Filters=['Name': 'instance-state-name','Values': ['stopped']])
    print("instance is stopped")
  
    #start Instance
    ec2.start_instances(InstanceIds=ids)
    waiter = ec2.get_waiter('instance_running')
    waiter.wait(Filters=['Name': 'instance-state-name','Values': ['running']])
    print("instance is started and running")

【问题讨论】:

我认为服务员代码应该是:waiter.wait(InstanceIds=ids) 正如上面评论中提到的,你还没有告诉服务员等待哪个实例。 感谢您的反馈,这是问题所在并已修复 【参考方案1】:

我调整了您的代码并在 Cloud Shell 中进行了测试。有关服务员的更多详细信息,您应该查看文档here

import boto3
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
  
    ids = ['i-0d01a6288188f08ce']

    #stop Instance
    ec2.stop_instances(InstanceIds=ids)
    instance_stopped_waiter = ec2.get_waiter('instance_stopped')
    instance_stopped_waiter.wait(InstanceIds=ids)
    print("instance is stopped")
        
    #start Instance
    ec2.start_instances(InstanceIds=ids)
    instance_runner_waiter = ec2.get_waiter('instance_running')
    instance_runner_waiter.wait(InstanceIds=ids)
    print("instance is started and running")

【讨论】:

此解决方案有效。非常感谢

以上是关于Boto3 get_waiter 不会正确停止和启动实例的主要内容,如果未能解决你的问题,请参考以下文章