Reputation: 91
Our previous Devops created several Key Pairs in EC2. It looks like some of them are not used anymore. So I would like to delete them. How can I find when the Keypairs were created and if they are currently used (preferably in the Console)?
Upvotes: 9
Views: 5637
Reputation: 3973
This will provide a list of AWS KeyPairs
that are in use.
aws ec2 --profile default describe-key-pairs --query KeyPairs[].[KeyName] --output text |xargs -I {} aws ec2 --profile default describe-instances --filters Name=key-name,Values={} --query Reservations[].Instances[].[KeyName,InstanceId] --output text| uniq
It gets a list of KeyPairs
and uses that output to match servers using those Keys
. If a KeyPair
is not used it will not appear in the list.
Output:
fake_key
second-fake-key
This will match servers that are shut off too.
And I wanted to see what this would look like in Python
so here you go. This will get a list of keys and output keys that are not used.
#! /usr/bin/env python
import boto3
region = 'us-east-1'
session = boto3.Session(profile_name='default')
ec2 = session.client('ec2')
response = ec2.describe_key_pairs()['KeyPairs']
for key in response:
found_instance = ec2.describe_instances(
Filters=[
{
'Name': 'key-name',
'Values': [key['KeyName']]
}
]
)['Reservations']
if len(found_instance) == 0:
print (key['KeyName'] + " is unused")
Output:
fake-key is unused
Upvotes: 10
Reputation: 269470
Keypairs are a feature of Linux, not AWS.
When an Amazon EC2 instance is launched from an Amazon Linux AMI, there is some code on the instance that copies the nominated keypair into the /users/ec2-user/.ssh/authorized_keys
file. After this, it is just normal Linux.
So, the only way to know if an instance permits login via a particular keypair is to look on every instance, in every user's .ssh/authorized_keys
file to look for that keypair.
It should be mentioned that AWS-generated keypairs are not a recommended way to manage logins to instances on an on-going basis. Your organization would probably have an Active Directory or LDAP server, so instances should be configured to use these authentication services rather than AWS keypairs. This way, it would be very simply to deactivate users in a central location rather than having to visit each instance individually.
Bottom line: Follow your normal security procedures on Amazon EC2 as well as on-premises.
Upvotes: 2
Reputation: 1425
Currently, AWS does not provide any way to retrieve the date and time as to when the Key Pair was created. In your case, what you can do is, check the key pairs created for the instances in the EC2 console and delete the rest of the key pairs which are not being used.
Upvotes: 0