Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
nos Avatar asked Aug 01 '17 23:08

nos


People also ask

How do I know if an EC2 instance has been terminated?

Open the CloudTrail console. Choose Event history. Select Event Name in the Filter dropdown list, and then enter TerminateInstances to view all instance termination API calls.

What happens when you terminate an EC2 instance?

When you terminate an EC2 instance, the instance will be shutdown and the virtual machine that was provisioned for you will be permanently taken away and you will no longer be charged for instance usage. Any data that was stored locally on the instance will be lost.

When an EC2 instance is terminated what is the best practice way to prevent all of the volume data from being erased?

You'll need to set the file's Delete on termination setting to False. You can find instructions for doing so on the Amazon EC2 documentation page. One more way that you can protect your EC2 instances against accidental data loss is to enable termination protection.


1 Answers

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.

like image 137
John Rotenstein Avatar answered Oct 03 '22 02:10

John Rotenstein