简体   繁体   中英

Boto3 get_waiter does not stop and start instance correctly

Problem: Hello I'm trying to stop and start instances in the same lambda function. I'm using waiters, however the code above only stops the instance, but doesn't start it back up as it does not wait for the stop. Please help me correct the code, thank you

Code:

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")

I adjusted your code and tested in Cloud Shell. For more details on waiters you should check out the documentation 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM