Created
November 27, 2020 13:45
-
-
Save alces/95275e90a21dad3a253ad359917e8007 to your computer and use it in GitHub Desktop.
Print out "creation time" for EC2 instances (in reality, it's the first network interface attachement time)
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 | |
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