【问题标题】:Boto3 get_waiter does not stop and start instance correctlyBoto3 get_waiter 不会正确停止和启动实例
【发布时间】: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)
  • 正如上面评论中提到的,你还没有告诉服务员等待哪个实例。
  • 感谢您的反馈,这是问题所在并已修复

标签: python amazon-web-services amazon-ec2 aws-lambda boto3


【解决方案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")

【讨论】:

  • 此解决方案有效。非常感谢
猜你喜欢
  • 2022-07-03
  • 2017-11-28
  • 2021-05-27
  • 2019-08-03
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2018-08-15
相关资源
最近更新 更多