Hi all, today we are going to perform an automation stuff. Using this script we will be going to delete all unused key pair from our AWS account using boto3. By doing this we can ensure that our AWS account remains secure to some extent.
Checking all key pairs
Firstly we will be writing code to see our all key pairs that exist with the aws account. Below is the code.
import boto3 session = boto3.Session() # Creating empty lists for all, used, and unused key pairs key_pairs =  used_key_pairs =  unused_key_pairs =  # List the key pairs in the selected region ec2 = session.client('ec2') key_pairs = list(map(lambda i: i['KeyName'], ec2.describe_key_pairs()['KeyPairs'])) print(key_pairs)
Below is the code output. I am getting awslearning1, check-1 and check-2
Below is the picture of my aws account showing the same 3 key pairs.
Listing all Used Key Pair
Now we are going to list all used key pairs.
ec2 = session.client('ec2') instance_groups = list(map(lambda i: i['Instances'], ec2.describe_instances()['Reservations'])) for group in instance_groups: for i in group: if i['KeyName'] not in used_key_pairs: used_key_pairs.append(i['KeyName']) print(used_key_pairs)
Below pic shows the code output i am getting. As i only have one used key pair associated with one of my ec2 instance.
Finding and deleting all unused key pairs
Since we have listed listed all key pairs and used key pairs, we can easily fetch unused key pairs. so, we will be first finding that and deleting the unused key pairs.
for key in key_pairs: if key not in used_key_pairs: unused_key_pairs.append(key) print(unused_key_pairs)
Now we have the unused key pairs. Lastly we will be deleting these unused key pairs.
for key in unused_key_pairs: print(key) ec2.delete_key_pair(KeyName=key)
The above pic is the code output. You can now see that both unused key pairs have been delete from my aws account.
In this blog we have seen how to list all key pairs, used key pairs and finally unused key pairs from your AWS account. For the security purposes it is recommended not to have unused key pairs in your AWS account. After listing unused key pairs , we have learned how to delete them also. All by using boto3 package of python. You can automate this stuff also. For more detalis about key pair please visit https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html
Please visit https://blog.knoldus.com/tag/aws/ for more blogs on AWS