Over time, it’s common to accumulate unused EC2 keypairs from EC2 instances that might not be running on your AWS account anymore.
Keeping these unused keypairs can create unnecessary clutter and increase security risks.
In this guide, we’ll walk through how to use a Python script with Boto3 to find and delete all unused EC2 keypairs across all AWS Regions.
Table of Contents
How to delete unused Amazon EC2 keypairs across all AWS regions
Before you can start, you’re required to have done the following prerequisites before you can run the Python script on your AWS account.
- Install the AWS CLI and configure an AWS profile
- Setting up the Python Environment
If you’ve already done this, you can proceed to step 3.
1. Install AWS CLI and configure an AWS profile
The AWS CLI is a command line tool that allows you to interact with AWS services in your terminal. Depending on if you’re running Linux, macOS, or Windows the installation goes like this:
# macOS install method:
brew install awscli
# Windows install method:
wget https://awscli.amazonaws.com/AWSCLIV2.msi
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
# Linux (Ubuntu) install method:
sudo apt install awscli
In order to access your AWS account with the AWS CLI, you first need to configure an AWS Profile. There are 2 ways of configuring a profile:
- Access and secret key credentials from an IAM user
- AWS Single Sign-on (SSO) user
In this article, I’ll briefly explain how to configure the first method so that you can proceed with running the python script on your AWS account.
If you wish to set up the AWS profile more securely, then I’d suggest you read and apply the steps described in setting up AWS CLI with AWS Single Sign-On (SSO).
In order to configure the AWS CLI with your IAM user’s access and secret key credentials, you need to login to the AWS Console.
Go to IAM > Users, select your IAM user, and click on the Security credentials tab to create an access and secret key.
Then configure the AWS profile on the AWS CLI as follows:
➜ aws configure
AWS Access Key ID [None]: <insert_access_key>
AWS Secret Access Key [None]: <insert_secret_key>
Default region name [None]: <insert_aws_region>
Default output format [json]: json
Your was credentials are stored in ~/.aws/credentials and you can validate that your AWS profile is working by running the command:
➜ aws sts get-caller-identity
{
"UserId": "AIDA5BRFSNF24CDMD7FNY",
"Account": "012345678901",
"Arn": "arn:aws:iam::012345678901:user/test-user"
}
2. Setting up the Python Environment
To be able to run the Python Boto3 script, you will need to have Python installed on your machine.
Depending on if you’re running Linux, macOS, or Windows the installation goes like this:
# macOS install method:
brew install python
# Windows install method:
wget https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe
msiexec.exe /i https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
# Linux (Ubuntu) install method:
sudo apt install python3 python3-pip
Once you have installed Python, you will need to install the Boto3 library.
You can install Boto3 using pip, the Python package manager, by running the following command in your terminal:
pip install boto3
3. Create Python Script to delete all unused Amazon EC2 keypairs across all AWS regions
Once you have our environment set up, you can create the Python script.
Copy the following code into a new file on the desired location and name it: delete_all_unused_keypairs.py
.
# https://github.com/dannysteenman/aws-toolbox
#
# License: MIT
#
# This script finds and deletes all unused EC2 keypairs in all AWS Regions
import boto3
ec2 = boto3.resource("ec2")
unused_keys = {}
for region in ec2.meta.client.describe_regions()["Regions"]:
region_name = region["RegionName"]
try:
ec2conn = boto3.resource("ec2", region_name=region_name)
key_pairs = ec2conn.key_pairs.all()
used_keys = set([instance.key_name for instance in ec2conn.instances.all()])
for key_pair in key_pairs:
if key_pair.name not in used_keys:
unused_keys[key_pair.name] = region_name
key_pair.delete()
print(
f"Deleted unused key pair {key_pair.name} in region {region_name}"
)
except Exception as e:
print(f"No access to region {region_name}: {e}")
print(f"Found and deleted {len(unused_keys)} unused key pairs across all regions:")
print(unused_keys)
This script uses Boto3 to iterate through all AWS Regions and find unused EC2 keypairs.
If a keypair is not in use, it will be deleted, and the script will print out a message confirming the deletion.
4. Run the Python Boto3 script in your AWS account
To run the script, simply execute the following command in your terminal or command prompt:
python delete_all_unused_keypairs.py
The script starts running and will iterate through each AWS Region, find any unused EC2 keypairs, and delete them.
➜ python delete_all_unused_keypairs.py
Deleted unused key pair test1 in region eu-central-1
Deleted unused key pair test2 in region eu-central-1
Deleted unused key pair test3 in region eu-central-1
Deleted unused key pair test4 in region us-east-1
Deleted unused key pair test5 in region us-east-1
Found and deleted 5 unused key pairs across all regions:
{'test1': 'eu-central-1', 'test2': 'eu-central-1', 'test3': 'eu-central-1', 'test4': 'us-east-1', 'test5': 'us-east-1'}
You will see a message confirming each deletion, along with a summary of the total number of unused keypairs found and deleted across all regions.
Conclusion
In this guide, we’ve walked through how to use a Python script with Boto3 to find and delete all unused EC2 keypairs across all AWS Regions.
This can help to reduce clutter and improve security within your AWS environment.
Remember to periodically run this script to ensure that any unused keypairs are promptly cleaned up.
Finally, always make sure to test your code before executing it in production and make sure to double-check your permissions before running any scripts that can modify your AWS environment.