homeblogdelete unused key pairs with python

The Key to Securing Your AWS Account

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.

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

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.

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.

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:

Find the whole Python script here