Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Print out "creation time" for EC2 instances (in reality, it's the first network interface attachement time)
import boto3
import datetime
# iterator over EC2 instances for region
def ec2_instances(region):
client = boto3.client('ec2', region_name = region)
for reservation in client.describe_instances().get('Reservations', []):
for instance in reservation.get('Instances', []):
yield instance
# iterator over EC2 regions
def ec2_regions():
for region in boto3.client('ec2').describe_regions().get('Regions', []):
yield region
# Name tag of EC2 instance
def instance_name(instance):
tags = {t['Key']: t['Value'] for t in instance.get('Tags', [])}
return tags.get('Name', 'NONAME')
# AttachTime for EC2 instance primary interface
def net_attach_time(instance):
default_time = datetime.datetime.now()
for interface in instance.get('NetworkInterfaces', []):
attachement = interface.get('Attachment', {})
if attachement.get('DeviceIndex') == 0:
return attachement.get('AttachTime', default_time)
return default_time
def lambda_handler(event, context):
for region in (r['RegionName'] for r in ec2_regions()):
print(region)
for instance in ec2_instances(region):
print(' %s: %s' % (instance_name(instance), net_attach_time(instance)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment