How to sort stopped EC2s by time using "state_transition_reason" variable? Python Boto3
Question: I am seeing a steep increase on my AWS account costs. The largest cost items
are: **EC2: 67% RDS: 12%**

I have more than 50 stopped EC2s. One of them has been sitting there in a
stopped state from September of the year 2015.

I found the way to get the stopped time of EC2s using variable called:

> state_transition_reason

Here how the code looks:

    
    
    import boto3
    
    session = boto3.Session(region_name="us-east-1")
    ec2 = session.resource('ec2')
    
    instances = ec2.instances.filter(
                Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
    
    count = 0
    
    for i in instances:
       print "{0}, {1}, {2}".format( i.id, i.state_transition_reason, i.state['Name']) 
       count +=1
    
    print count
    

It prints out the following information:

    
    
    i-pll78233b, User initiated (2016-07-06 21:14:03 GMT), stopped
    i-tr62l5647, User initiated (2015-12-18 21:35:20 GMT), stopped
    i-9oc4391ca, User initiated (2016-03-17 04:37:46 GMT), stopped
    55
    

**My question is** : How can I sort instances (EC2s) by their time being
stopped. In my example I would love to see the output in the following order
starting from year 2015 accordingly:

    
    
    i-tr62l5647, User initiated (2015-12-18 21:35:20 GMT), stopped
    i-9oc4391ca, User initiated (2016-03-17 04:37:46 GMT), stopped
    i-pll78233b, User initiated (2016-07-06 21:14:03 GMT), stopped
    55
    

Thanks.


Answer: As long as the User initiated part never varies, we can simply sort the
instances by state_transition_reason:

    
    
    sortedInstances = sorted(instances, key=lambda k: k.state_transition_reason) 
    

