Problem scenario
You want to write a Python program to delete servers. How do you delete EC-2 instances in AWS with Python?
Solution
Prerequisites
a. You have installed Boto3. If you do not know how, see this posting.
b. You know the instance IDs. If you do not know them, see this posting.
Procedures
Read the "Usage instructions" of this Python program we call "deleteec2.py". The content of this Python script is below.
""" Usage instructions
1. replace "aaa111" with the aws_access_key_id of your account
2. replace "bbb222" with the aws_secret_access_key of your account
If you are not sure how to find these credentials do the following:
To find the AWS Access Key ID and AWS Secret Access Key, in the AWS console, click on your name in the upper right hand corner.
Then click on "My Security Credentials." Click "Create New Access Key" Click "Show Access Key."
3. Replace us-west-1 with the region that you want to list EC-2 instances for.
4. Replace i-1234abcd with the instance ID of the server you want to delete. If you have multiple servers, place the instance IDs in single quotes and separate those quoted strings by commas inside the square brackets.
5. To run it, call it deleteec2.py and run it with a command like this: "python deleteec2.py"
"""
import boto3
ec2 = boto3.resource('ec2', aws_access_key_id=' aaa111', aws_secret_access_key=' bbb222', region_name='us-west-1')
alist = ['i-1234abcd'] # alist = ['i-1234abcd','i-5678-efgh'] is how multiple servers are deleted
ec2.instances.filter(InstanceIds=alist).stop()
ec2.instances.filter(InstanceIds=alist).terminate()