DEV Community

Discussion on: Simple EC2 Stopinator in Lambda

Collapse
 
qfarhanm profile image
Mohammed Farhan

Hi,

Hoping you can provide a solution to my ask.

So, I have an ask to terminate all the EC2 instances that haven't been started in the past 30 days. Basically all it is that if an EC2 instance is in a stopped state for 30 days, it needs terminating.

I have gone through your stopinator article (which is cool by the way).

How can I proceed with my ask?

One solution that I have is scheduling an even in AWS Eventbridge using the cron job to trigger a lambda function (python code) to check the instance state of the ec2s and terminate any that have been in a stopped state for 30 days.

One drawback that I have is that these instances are not tagged and even if they are, the tags make no sense.

I have found a code but unsure if it will work?

import boto3
import re
from datetime import datetime

TERMINATION_AGE = 30

ec2_client = boto3.client('ec2', region_name='ap-southeast-2')

Get a list of stopped instances

instances = ec2_client.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])

for reservation in instances['Reservations']:
for instance in reservation['Instances']:

    # StateTransitionReason might be like "i-xxxxxxxx User initiated (2016-05-23 17:27:19 GMT)"
    reason = instance['StateTransitionReason']
    date_string = re.search('User initiated \(([\d-]*)', reason).group(1)
    if len(date_string) == 10:
        date = datetime.strptime(date_string, '%Y-%m-%d')

        # Terminate if older than TERMINATION_AGE
        if (datetime.today() - date).days > TERMINATION_AGE:
            ec2_client.terminate_instance
Enter fullscreen mode Exit fullscreen mode