Skip to content

Instantly share code, notes, and snippets.

@mebeling
Created October 6, 2015 19:24
Show Gist options
  • Save mebeling/ce61395c117d53a8d7ce to your computer and use it in GitHub Desktop.
Save mebeling/ce61395c117d53a8d7ce to your computer and use it in GitHub Desktop.
Comma separated value summary of EC2 instances in the dev, prod, platdev, dmz accounts
#!/usr/local/bin/python
#
# Requires boto3
# Expects AWS profiles:
# dev, prod, platdev, dmz
# AWS profile configs are in ~/.aws/config and ~/.aws/credentials
import boto3
def gatherEc2Info( profile, region ):
ec2data = {}
awsSession = boto3.session.Session(profile_name=profile, region_name=region)
ec2 = awsSession.resource('ec2')
reservations = ec2.meta.client.describe_instances()
for r in reservations['Reservations']:
for i in r['Instances']:
ec2data[i['InstanceId']] = {}
ec2data[i['InstanceId']]['type'] = i['InstanceType']
ec2data[i['InstanceId']]['az'] = i['Placement']['AvailabilityZone']
ec2data[i['InstanceId']]['tenancy'] = i['Placement']['Tenancy']
# Set empty defaults so these keys exist
ec2data[i['InstanceId']]['name'] = ''
ec2data[i['InstanceId']]['env'] = ''
ec2data[i['InstanceId']]['role'] = ''
ec2data[i['InstanceId']]['privateip'] = ''
ec2data[i['InstanceId']]['publicip'] = ''
# Override the default empty values if tags are set
if 'Tags' in i:
for t in i['Tags']:
if 'Name' == t['Key']:
ec2data[i['InstanceId']]['name'] = t['Value']
if 'env' == t['Key']:
ec2data[i['InstanceId']]['env'] = t['Value']
if 'role' == t['Key']:
ec2data[i['InstanceId']]['role'] = t['Value']
if 'PrivateIpAddress' in i:
ec2data[i['InstanceId']]['privateip'] = i['PrivateIpAddress']
if 'PublicIpAddress' in i:
ec2data[i['InstanceId']]['publicip'] = i['PublicIpAddress']
ec2data[i['InstanceId']]['profile'] = profile
return ec2data
instanceData = {}
for profile in ['dev', 'prod', 'platdev', 'dmz']:
for region in ['us-east-1', 'us-west-1', 'us-west-2']:
instanceData.update(gatherEc2Info(profile, region))
print "instance_id,name,aws_account,AZ,type,tenancy"
for i in instanceData:
print "%s,%s,%s,%s,%s,%s" % (i,
instanceData[i]['name'],
instanceData[i]['profile'],
instanceData[i]['az'],
instanceData[i]['type'],
instanceData[i]['tenancy']
)
@sara4dev
Copy link

sara4dev commented Oct 6, 2015

good one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment