Secure your AWS Account by Removing Unused EC2 Key Pairs with Python

Cloud security is top of mind right now, given the various high-profile security breaches today. One overlooked source of potential vulnerabilities is unused EC2 Key Pairs. EC2 Key Pairs are used to configure an EC2 instance with SSH access and provide a convenient way to manage instances. However, when was the last time you performed an audit to make sure that the only key pairs in your account are given to active employees who have proper authorization to connect to instances? Are you sure all of those keys are even being used?

In this blog post, we’ll use a simple Python script to perform an audit of all EC2 key pairs in the account and determine which of those keys are not being used and delete them.

First, let’s find all the keys.

First, we configure the boto3 client to connect to our AWS account and allow us to start listing EC2 Key Pairs. We’ll also create 3 lists - one for storing all key pairs, one for used key pairs, and one for unused key pairs.

import boto3

sess = boto3.Session(
  *# TODO: Supply your AWS credentials & specified region here*
  aws_access_key_id='   MYAWSACCESSKEYID',
  aws_secret_access_key='MYSECRETACCESSKEY',
  region_name='us-east-1', *# Or whatever region you want*
)

# Creating lists for all, used, and unused key pairs
all_key_pairs = []
all_used_key_pairs = []
all_unused_key_pairs = []

Next, we make a call to get all the key pairs and filter for the key pair names:

# List the key pairs in the selected region
ec2 = sess.client('ec2')
all_key_pairs = list(map(lambda i: i['KeyName'], ec2.describe_key_pairs()['KeyPairs']))

Second, let’s find all the key pairs in use.

In order to find all the key pairs currently in use, we first list the EC2 instances and then inspect those instances for their key pair.

# Each EC2 reservation returns a group of instances.
instance_groups = list(map(lambda i: i['Instances'], ec2.describe_instances()['Reservations']))

# Create a list of all used key pairs in the account based on the running instances
for group in instance_groups:
  for i in group:
    if i['KeyName'] not in all_used_key_pairs:
      all_used_key_pairs.append(i['KeyName'])

Next, compare the lists.

We compare each key pair in all_key_pairs to the list of used key pairs. If the key pair is not being used, we add it to the list of unused key pairs.

# Now compare the two lists
for key in all_key_pairs:
  if key not in all_used_key_pairs:
    all_unused_key_pairs.append(key)

Finally, we delete the unused key pairs.

We delete the unused key pairs by iterating over the list of unused key pairs and calling the ec2.delete_key_pair() function:

# Delete all unused key pairs
print('Deleting unused key pairs:')
for key in all_unused_key_pairs:
  print(key)
  ec2.delete_key_pair(KeyName=key)

Find the whole Python script here

Conclusion

Deleting unused key pairs is a good practice to ensure that no one is granted unauthorized access to your instances. Want to run this workflow on a schedule? Invite other people on your team to kick off workflows? Notify your team in Slack when key pairs are deleted? That’s why we built Relay.

We built this workflow out for you so you don’t have to – try it out here.

To learn more about the product, sign up for our updates on relay.sh. Our mission is to free you of tedious cloud-native workflows with event-driven automation! For more content like this, please follow our blog.