Created
March 11, 2020 04:00
-
-
Save gweinhold/acbce4a57a42e43b0c8cfe721e4fd18b to your computer and use it in GitHub Desktop.
outputs keypairs registered in region and what's in use for ec2 instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'] | |
def get_hostname(instance): | |
if instance.tags: | |
for tag in instance.tags: | |
if tag["Key"] == 'Name': | |
return tag["Value"] | |
return "Unknown" | |
def get_keys_in_use(regions): | |
print("Getting keys in use by instances") | |
keys_with_regions = {} | |
for region in regions: | |
key_names = set() | |
ec2 = boto3.resource('ec2', region_name=region) | |
instances = ec2.instances.filter( | |
Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}]) | |
for instance in instances: | |
hostname = get_hostname(instance) | |
if instance.key_name: | |
key_names.add(instance.key_name) | |
print(f"Region: {region} InstanceId: {instance.id} Key: {instance.key_name} Name: {hostname} State: {instance.state['Name']}") | |
keys_with_regions[region] = list(key_names) | |
print(keys_with_regions) | |
def get_keys_for_regions(regions): | |
print("Gettings keys registered in AWS Region") | |
keys_with_regions = {} | |
for region in regions: | |
key_names = [] | |
print(f'Checking {region}') | |
ec2 = boto3.client('ec2', region_name=region) | |
response = ec2.describe_key_pairs() | |
for key in response['KeyPairs']: | |
#Add key name to list | |
key_names.append(key['KeyName']) | |
#Add keys for region to master dictionary | |
keys_with_regions[region] = key_names | |
#All Keys across regions | |
print(keys_with_regions) | |
get_keys_in_use(regions) | |
get_keys_for_regions(regions) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment