What is the correct way to verify that an AWS EC2 instance has completed successfully using boto3?

I am using the following code to terminate an EC2 aws instance. What is the correct way to check if the completion is complete?

s = boto3.Session(profile_name='dev')
ec2 = s.resource('ec2', region_name='us-east-1')
ins = ec2.Instance(instance_id)
res = ins.terminate()

      

Should I check

res['TerminatingInstances'][0]['CurrentState']['Name']=='shutting-down'

Or ignore res

and describe the instance again to check?

+3


source to share


1 answer


The best way is to use a waiterEC2.Waiter.InstanceTerminated

.

It polls EC2.Client.describe_instances()

every 15 seconds until a successful state is reached. Error after 40 failed checks.



import boto3

client = boto3.client('ec2')
waiter = client.get_waiter('instance_terminated')

client.terminate_instances(InstanceIds=['i-0974da9ff5318c395'])
waiter.wait(InstanceIds=['i-0974da9ff5318c395'])

      

The program exited as soon as the instance was in a terminated state.

+2


source







All Articles