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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With