nos
nos

Reputation: 20872

what's the proper way to check if terminating AWS EC2 instance is successful using boto3?

I use the following code to terminate an aws EC2 instance. What is the proper way to check whether the termination is successful?

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 whether

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

Or ignore res and describe the instance again to check?

Upvotes: 7

Views: 5612

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269410

The best way is to use the EC2.Waiter.InstanceTerminated waiter.

It polls EC2.Client.describe_instances() every 15 seconds until a successful state is reached. An error is returned 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 once the instance was in the terminating state.

Upvotes: 14

Related Questions