Boto3 get_waiter 无法正确停止和启动实例

Boto3 get_waiter does not stop and start instance correctly

问题: 您好,我正在尝试在同一个 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")

我调整了你的代码并在 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")