So I have my python script which lists a report about each ec2 instance. I have a function which sorts the networkattatchtime of an instance but everytime i use stftime to format the output of the date , it seems to mess up the sorting and lists instances in a random order and not by the most oldest CreationDateTime. The output i get is as follows :
i-09dc54328002240ff,Aug 05 2021,asg-workxxx
i-048e92c5a4741d2b1,Mar 09 2017,False
i-0d649cebdf54bd2f4,Mar 12 2020,asg-dyyyyy
i-0ff596f1dc01b61d8,Mar 17 2021,asg-base-test
i-06db4eb158ad0b071,May 12 2021,False
i-0f285277529543462,May 18 2018,False
i-0f67cf99fb9f96c3f,Oct 14 2020,asg-elk-test
i-01734dfef0159c5c8,Oct 20 2020,asg-lb-test
i-0539c8dfc839cbfda,Oct 26 2020,asg-stand-base-test
You can see the CreationDateTime are not in a sorted order.
My code is as follows :
response = ec2_client.describe_instances(
MaxResults=10
)
# return json data from describe instances and filter what is needed
instances = (len(response['Reservations']))
header_row = 'InstanceID, CreationDateTime, AutoScalingGroupName' + '\n'
for x in range(instances):
# Get InstanceId
instance_id = (response['Reservations'][x]
['Instances'][0]['InstanceId'])
# Get NetworkInterfacws AttatchTime
network_interface_id = (
response['Reservations'][x]['Instances'][0]['NetworkInterfaces'][0]['NetworkInterfaceId'])
network_interface_details = ec2_client.describe_network_interfaces(
NetworkInterfaceIds=[network_interface_id])
networkinterface_id_attachedtime = network_interface_details[
'NetworkInterfaces'][0]['Attachment']['AttachTime']
time_between_insertion = datetime.now(
timezone.utc) - networkinterface_id_attachedtime
# Get Autoscaling GroupName
tags = (response['Reservations'][x]['Instances'][0]['Tags'])
autoscaling_group_name = get_tag(tags, 'aws:autoscaling:groupName')
# print results
if time_between_insertion.days > max_age:
line = '{},{},{}'.format(
instance_id, formatted_date_networkinterface_id, autoscaling_group_name)
instances_list.append(line)
sorted_list= sorted(instances_list, key=lambda v: v.split(',')[1])
for instance in sorted_list:
print(instance) ```
sorted(instances_list, key=lambda v: v.split(',')[1])so there is no "date" per se. Note in your output the "A" month dates appear first...