Home > Software engineering >  Boto3 get_waiter does not stop and start instance correctly
Boto3 get_waiter does not stop and start instance correctly

Time:12-21

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

CodePudding user response:

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