Created
January 5, 2018 01:51
-
-
Save garyellis/d89b99a689f1ac6df0058a8b1d2b1f16 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# a quick script to export all instances from all regions to csv | |
import os | |
import boto3 | |
from botocore.exceptions import ClientError | |
from datetime import datetime, timedelta | |
import logging | |
import sys | |
import csv | |
logging.getLogger('botocore').setLevel(logging.CRITICAL) | |
log = logging.getLogger() | |
log.handlers = [] | |
handler = logging.StreamHandler(sys.stdout) | |
formatter = logging.Formatter( | |
'%(asctime)4s %(name)4s [%(filename)s:%(lineno)s - %(funcName)s()] %(levelname)4s %(message)4s') | |
handler.setFormatter(formatter) | |
log.addHandler(handler) | |
log.setLevel(logging.INFO) | |
def get_tag_value(tags, key='Name'): | |
""" | |
returns the value of the given tag | |
""" | |
value = 'Null' | |
if tags: | |
for tag in tags: | |
if key in tag['Key']: | |
value = tag['Value'] | |
return value | |
def get_ami_name(instance_resource): | |
""" | |
Get the AMI name from the instance resource | |
""" | |
ami_name = '' | |
try: | |
ami_name = instance_resource.image.name | |
except AttributeError: | |
pass | |
return ami_name | |
def __get_ec2_instance_resources(session_config): | |
""" | |
Returns a collection of ec2 instances resource | |
""" | |
session = boto3.session.Session(**session_config) | |
try: | |
instances = [i for i in session.resource('ec2').instances.all()] | |
except ClientError as err: | |
log.error(err) | |
raise | |
return instances | |
def get_regions(): | |
""" | |
return available regions | |
""" | |
regions = [] | |
try: | |
for region in boto3.client('ec2').describe_regions()['Regions']: | |
regions.append(region['RegionName']) | |
except: | |
raise | |
return regions | |
def get_aws_account(): | |
""" | |
Get the current account | |
""" | |
sts_client = boto3.client('sts') | |
account_id = sts_client.get_caller_identity()["Account"] | |
return account_id | |
def get_ec2_instances(profile=None): | |
""" | |
returns a list of ec2 instances | |
""" | |
aws_profile = profile or os.environ.get('AWS_DEFAULT_PROFILE') | |
ec2_headers = ['aws_profile', 'region', 'ami_id', 'ami_name', 'instance_id', 'instance_type', 'tag_Name', 'architecture', 'state', 'launch_time'] | |
ec2_instances = [] | |
ec2_instances.append({'headers': ec2_headers}) | |
for region in get_regions(): | |
log.info('Fetching instances in {}/{}'.format(profile, region)) | |
# setup our session parameters | |
session_config = {'profile_name': profile, 'region_name': region } | |
for i in __get_ec2_instance_resources(session_config): | |
ec2_instances.append( | |
{ | |
'aws_profile': aws_profile, | |
'region': region, | |
'ami_id': i.image_id, | |
'ami_name': get_ami_name(i), | |
'instance_id': i.instance_id, | |
'instance_type': i.instance_type, | |
'tag_Name': get_tag_value(i.tags), | |
'architecture': i.architecture, | |
'state': i.state['Name'], | |
'launch_time': i.launch_time | |
} | |
) | |
log.info('Found instances {}'.format(len(ec2_instances) -1)) | |
log.info('Total instances found in {} {}'.format(profile, len(ec2_instances) -1)) | |
return ec2_instances | |
def main(): | |
""" | |
""" | |
with open('config', 'r') as f: | |
config = f.readlines() | |
for i, profile in enumerate(config): | |
instances = get_ec2_instances(profile.strip()) | |
if i == 0: | |
to_csv(instances, True) | |
else: | |
to_csv(instances) | |
def to_csv(records, headers=False): | |
""" | |
export a list of dict records to csv | |
""" | |
fileout = './ec2_instances.csv' | |
fields = records.pop(0) | |
log.info('Writing records to csv') | |
with open(fileout, 'a') as f: | |
writer = csv.DictWriter(f, fieldnames=fields['headers'], lineterminator='\n') | |
if headers: | |
writer.writeheader() | |
writer.writerows(records) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment